-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!

2
  • 7
    If you stored list1 in a dictionary instead, you'd not have this problem. Keep your data out of your variable names. Commented May 3, 2014 at 14:12
  • @MartijnPieters I've finally stopped misspelling your name! I think I spend too much time on SO........ Commented May 3, 2014 at 14:22

4 Answers 4

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.

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

Comments

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.

Comments

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.

Comments

0
In [7]: a = "foo"

In [8]: b = "a"

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

But you shouldn't have to do this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.