Python Random Pick From List Without Previous Pick
I have a list and I randomly print one of its items, but I want to print another random item from the list and I want to be 100% sure it's not the previous one. import random i = 0
Solution 1:
Use random.sample to select unique elements from a given sequence, like this
import random
Names = ['Andrew', 'John', 'Jacob', 'Bob']
choice = random.sample(Names, 2) # choose 2 unique names from Names
print(choice[0])
print(choice[1])
Solution 2:
random.shuffle(names)
names[0] # first pick
names[1] # second pick ... also guaranteed not to be first pick
another alternative is to remove the names from the list as you randomly pick them
names =[...]
random1 = names.pop(random.randint(0,len(names)))
random2 = names.pop(random.randint(0,len(names)))
Post a Comment for "Python Random Pick From List Without Previous Pick"