3

Is there a way to pass a variable to the choice() function for a list. I have a bunch of lists and I want to randomly select from one list and then use the string that is returned to select from a list that has that string name.

A = ['1','2','3']

print choice (A) - this gets me a random choice from the list

but I want to to store the choice as a variable and use it to call another list

A = ['1','2','3']
1 = ['A','B','C']

Var1 = choice (A)

print choice (Var1) *** this is my problem, how do I pass a variable to the choice function

Thanks for the help!

Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
English Grad
  • 1,365
  • 5
  • 21
  • 40

2 Answers2

11

In Python, you can do this using references.

A = [1, 2, 3]
B = [4, 5, 6]
C = [7, 8, 9]
MasterList = [A, B, C]

whichList = choice(MasterList)
print choice(whichList)

Note that A, B, C are names of previously assigned variables, instead of quoted strings. If you ever find yourself using quoted names to refer to variables, there's usually a better way to do whatever you're trying to do.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 6
    "If you ever find yourself using quoted names to refer to variables, there's usually a better way to do whatever you're trying to do." +10 – DSM Jan 29 '12 at 19:25
1
some_list = { 'A': ['1','2','3'],
    'B': [some_other_list],
    'C': [the_third_list]
}
var1= choice( ['A', 'B', 'C'] ) # better: some_list.keys()
print( choice (some_list[var1])

"If you ever find yourself using quoted names to refer to variables, there's usually a better way to do whatever you're trying to do."

90% of the time, you should be using a dictionary. The other 10% of the time, you need to stop what you're doing entirely.

S.Lott
  • 384,516
  • 81
  • 508
  • 779