teaLeef
teaLeef

Reputation: 1989

Randomly choosing two elements in a list

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

Answers (1)

Martijn Pieters
Martijn Pieters

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

Related Questions