0

Looking for a help / solution here.

a = [1,2,3] b = [1,2,3] c = [1,2,3] d = [a,b,c] random.choice(random.choice(d)) 

this gives me 1,2 or 3. But how to find which list variable this random function used out of a, b, c ? how can I use or what is the syntax of the index function for this ? for my program I have to pop the element the random choice returns.

1
  • So just pop directly from the list object that random.choice() gave you. You don't need the variable name, only the list object itself. Commented Jun 4, 2017 at 14:57

1 Answer 1

4

If you want to remove something from the randomly chosen list, you don't need to have the variable name. The list object itself will do.

In other words, just remove the selected number from the result that random.choice() gives you:

picked_list = random.choice(d) picked = random.choice(picked_list) picked_list.remove(picked) 

If you must have some kind of name, don't use separate variables for the input lists. Use a dictionary:

lists = { 'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3], } list_picked = random.choice(lists) # returns 'a', 'b', or 'c' picked = random.choice(lists[list_picked]) lists[list_picked].remove(picked) 

Note that it'll be more efficient to just shuffle your lists up-front (putting them in random order), then pop elements as you need them:

d = [a, b, c] for sublist in d: random.shuffle(sublist) # later on picked = random.choice(d).pop() # remove the last element 

You'll have to figure out what it means to have an empty list there though.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. This one absolutely meets my coding criteria.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.