-5

I have:

Variable1 = "list1"

and

list1 = ["a", "b", "c", "d"]

How to access/manipulate list1 items (and apply all the standard list operator/functions to list1) via the variable Variable1

Something like

token = random.choice($UnknownOperator$(Variable1))
and token would be equal either to a b c or d 

Thanks!

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
MSA
  • 1
  • 1
  • 7
    If you stored `list1` in a *dictionary* instead, you'd not have this problem. [Keep your data out of your variable names](http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html). – Martijn Pieters May 03 '14 at 14:12
  • @MartijnPieters I've finally stopped misspelling your name! I think I spend too much time on SO........ – Adam Smith May 03 '14 at 14:22

4 Answers4

1

For that you can use globals():

x = "list1"

list1 = ["a", "b", "c", "d"]

>>> print globals()[x]
["a", "b", "c", "d"]

You can also do it as:

x = "list1"

list1 = ["a", "b", "c", "d"]

get_var = lambda a: globals()[a]

>>> print get_var(x)
["a", "b", "c", "d"]

>>> print random.choice(get_var(x))
c

But as @MartijnPieters said, dictionaries is a much better way to go.

sshashank124
  • 31,495
  • 9
  • 67
  • 76
1

The real answer to this question is, you don't. Use a dict.

lists = {'list1': ["a", "b", "c", "d"],
         'list2': ["foo", "bar", "baz"]}

token = random.choice(lists[Variable1])

All direct answers to this question are ugly hacks that make it hard for tools like editors, debuggers and code checkers to analyze your program.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1

For the RIGHT way to do this:

import random

dict_of_lists = {"list1":['a','b','c','d']}
variable_1 = "list1"

token = random.choice(dict_of_lists[variable_1])

Using the globals() dictionary, as many have pointed out, is a Bad Idea for the reason that Martijn Pieters gave in his comment to your question. Use a dictionary instead and key by the "variable name" you need to access.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
0
In [7]: a = "foo"

In [8]: b = "a"

In [9]: globals()[b]
Out[9]: 'foo'

But you shouldn't have to do this.

Grapsus
  • 2,714
  • 15
  • 14