Painko
Painko

Reputation: 15

Choosing random list

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

Upvotes: 1

Views: 66

Answers (2)

Mahrkeenerh
Mahrkeenerh

Reputation: 1121

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.

Upvotes: 2

user17066118
user17066118

Reputation:

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.

Upvotes: 0

Related Questions