2

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)
teaLeef
  • 1,879
  • 2
  • 16
  • 26

1 Answers1

5

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343