Kvintus
Kvintus

Reputation: 11

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
Names = ["Andrew", 'John', 'Jacob','Bob']

for l in Names:
    i += 1


c = random.randrange(0,i)
print(Names[c]) 

Upvotes: 1

Views: 133

Answers (2)

Adrian
Adrian

Reputation: 51

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])

Upvotes: 5

Joran Beasley
Joran Beasley

Reputation: 113930

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)))

Upvotes: 2

Related Questions