2

I want to have multiple variables that are set to random elements in the list. Right now I'm doing it somewhat like this:

from random import choice

list = ["a", "b"]
foo = choice(list)
bar = choice(list)
baz = choice(list) #etc.

I'm sure there is a better way to do this. I tried

 foo = bar = baz = choice(list)

but, of course it just sets them all to a single element of the list choosen once by random, and I want each variable to be set to new random.choice.

4 Answers 4

7

You can use random.sample() if you want to pluck out three distinct elements from the list (i.e. foo is never equal to bar, which might not be what you want):

foo, bar, baz = random.sample(l, 3)

I renamed your variable to l because list is a built-in type. Overriding it by accident won't be pretty.

3
  • The problem with sample is that it works "without replacement", i.e. won't work in case when you need more samples than there are elements in the original list. See docs.python.org/library/random.html#random.sample Of course it might work in this particular case (depends on the dataset and the needs), but it's worth noting.
    – kgr
    Commented Sep 14, 2012 at 8:25
  • sample() returns ValueError: "sample larger than population" in my case, since I have more variables than elements in the list.
    – M830078h
    Commented Sep 14, 2012 at 8:32
  • Alex's answer is the correct one. I misread the question...
    – Blender
    Commented Sep 14, 2012 at 8:35
5

maybe create a list with choice outputs? Something like

choices = [choice(list) for i in range(10)]

in which you have 10 elements? Also I would rename list to something else.

0
1

Like @Alex suggested but without getting list as result:

foo, bar, baz = [random.choice(list) for i in range(3)]
1

I would consider putting them in a dict then using somedict['foo'] style access:

from random import choice

CHOICES = ('a', 'b')
choices = {name: choice(CHOICES) for name in ['foo', 'bar', 'baz']}

Not the answer you're looking for? Browse other questions tagged or ask your own question.