Home > Back-end >  Choosing random list
Choosing random list

Time:10-08

I would like to randomly choose list as whole for example, I have lists with colors

list1 = ['blue','green']
list2 = ['red','yellow']

I have tried

random.choice(list1 or list2)

But it gives me random elemnt from them not the whole thing

CodePudding user response:

I tried to reproduce your example

random.choice(list1, list2)

but I was only getting an error. That's because random.choice() only accepts one argument - a sequence (a list). docs

Since you want to choose between two objects (lists), you have to make them into a sequence (e.g. tuple, list), and pass that into random.choice():

random.choice([list1, list2])

Now it will choose either from the two elements list1 and list2.

CodePudding user response:

You can put the list in another list, by doing either this:

listcontainer = [list1, list2]
random.choice(listcontainer)

or this, which is simpler:

random.choice([list1, list2])

The second option creates a new list (not assigned to a variable), that you can use in random.choice.

  • Related