Reputation: 23
I want to make a game of science bingo for my class. This code currently randomly picks an element from the list and displays it, but I don't know how to delete that value from the list so it is not randomly reprinted.
from random import randint
bingo=["H", "He", "C", "O"]
total=((len(bingo))-1)
while (total>0):
finish=input("Bingo?")
if (finish=="no"):
a=randint(0,int(total))
b=(bingo[int(a)])
print (b)
Upvotes: 0
Views: 120
Reputation: 45562
No need to delete from your list. Just shuffle it and iterate over it once. It will be faster and you can reuse your original list. So do random.shuffle(bingo)
then iterate over bingo
.
Here is how to incorporate this into your original code:
import random
bingo=["H", "He", "C", "O"]
random.shuffle(bingo)
for item in bingo:
if input("Bingo?") == "no":
print item
else:
break
Upvotes: 3
Reputation: 36892
If you want to do this once you have a couple of options
1) Use a random index and pop
import random
i = random.randrange(0, len(bingo))
elem = bingo.pop(i) # removes and returns element
2) use random choice them remove
import random
elem = random.choice(bingo)
bingo.remove(elem)
If you want all of the elements in a random order, then you're better off just shuffling the list and then either iterating over it, or repeatedly calling pop
import random
random.shuffle(bingo)
for elem in bingo: # list is not shuffled
...
or
import random
random.shuffle(bingo)
while bingo:
elem = bingo.pop()
...
Upvotes: 0
Reputation: 1623
foo = ['a', 'b', 'c', 'd', 'e']
from random import randrange
random_index = randrange(0,len(foo))
For displaying:
print foo[random_index]
For deletion:
foo = foo[:random_index] + foo[random_index+1 :]
Upvotes: -1