Reputation: 1989
Is there a better way to select two distinct elements from a list?
foo = ['1','a','3','f','ed']
elt1 = random.choice(foo)
elt2 = random.choice(foo)
while elt2 == elt1:
elt2 = random.choice(foo)
Upvotes: 2
Views: 3296
Reputation: 1121834
Yes, use random.sample()
:
elt1, elt2 = random.sample(foo, 2)
random.sample()
will pick k
unique elements from the given population, at random:
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Upvotes: 5