Question

I'd like to know which list python chooses with random.choice so I can use if statements for different outcomes.

thelists = [L1, L2, L3, L4, L5, L6]
theplayers = random.choice(thelists)

Id like to know which list, L1, L2..., the variable theplayers was chosen to be.

Was it helpful?

Solution 3

Have a look at the documentation:

random.choice(seq)

Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

Here, seq is your list.

You can get the index of the selected element with:

thelists.index(theplayers)

OTHER TIPS

Why not use random.randint instead, so you don't have to use list.index to find the list later:

from random import randint

# your list of lists
l = [[1,2,3],[4,5,6],[7,8,9]]
# choose a valid *index* into l, at random
index = randint(0,len(l) - 1)
# use the randomly chosen index to get a reference to the list
choice = l[index]

# write your conditionals which handle different choices
if index == 1:
    print 'first list'
elif index == 2:
    print 'second list'
...

This will be more efficient than using random.choice and then list.index each time you make a choice.

Quite simple:

 res = random.choice(my_list)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top