2

Suppose I have lists as follows:

candy = ['a','b','c']
fruit = ['d','e','f']
snack = ['g','h','i']

and a string

name = 'fruit'

I want to use string name for accessing list and it's content. In this case it should be fruit. I will use name for iterating list. As:

for x in name:
    print x
  • 3
    You can do this with eval but I'd suggest using dictionaries to hold those lists instead. – ayhan Jun 09 '16 at 05:37
  • 1
    With more emphasis: you **do not use a string value as a variable name in python**. Python has powerful tools and data structures, use them instead. – spectras Jun 09 '16 at 06:14
  • @spectras Please give me reference of data structures I can use in lieu of it. – Muhammad Yaseen Khan Jun 09 '16 at 06:26
  • [Python Datastructures](https://docs.python.org/3/tutorial/datastructures.html), or [this dict tutorial](http://learnpythonthehardway.org/book/ex39.html). – spectras Jun 09 '16 at 06:40

3 Answers3

12

You can use globals() like so:

for e in globals()[name]:
    print(e)

Output:

d
e
f

And if your variables happen to be in some local scope you can use locals()

OR you can create your dictionary and access that:

d = {'candy': candy, 'fruit': fruit, 'snack': snack}
name = 'fruit'

for e in d[name]:
    print(e)
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
  • 3
    Seriously, use this instead of `eval`, especially if the value passed in will be from the user - which lets the user effectively run everything which is a **huge** security risk. Though using a `dict` will be better. – metatoaster Jun 09 '16 at 05:44
  • @metatoaster I think that comment of yours should be on the OP's question, don't you think? ;-) Thanks. – Sнаđошƒаӽ Jun 09 '16 at 05:52
  • Indeed. But this question and its answers are a textbook example of giving a detailed explanation to someone asking how to shoot himself in the foot. – spectras Jun 09 '16 at 06:11
  • using `globals()` is nice idea. – Muhammad Yaseen Khan Jun 09 '16 at 06:40
  • @MuhammadYaseenKhan> no it's not. It exposes many, many variables, including imported modules and internal python variables. Just to get a dictionary, so why not use a dictionary in the first place? That's what they are for. – spectras Jun 09 '16 at 06:44
  • @spectras What do you mean by it "exposes many, many variables, including imported modules and internal python variables"? Aren't they already "exposed", as you call it, *inside* `globals()` which *is* a dictionary by the way? – Sнаđошƒаӽ Jun 09 '16 at 08:52
  • @MuhammadYaseenKhan If you think so, then go ahead and mark it as accepted ;-) – Sнаđошƒаӽ Jun 09 '16 at 08:55
  • 1
    @Sнаđошƒаӽ> That's my exact point, you don't want to expose `globals()` to random peeking from outside your program. Here the key *very* probably comes from an external source. Using an actual dictionary would ensure someone cannot pass, say, `__sys__`, `math` or `subprocess` or `PASSWORD` as a name and mess up the modules or gather internal information. – spectras Jun 09 '16 at 10:07
  • @spectras In my answer I have included something making use of user's own dictionary too. Your information seems useful anyway. Thanks. – Sнаđошƒаӽ Jun 09 '16 at 10:52
  • @Sнаđошƒаӽ I probably should elaborate more: `locals()` is the way over `globals()` if OP *must* keep using standard variables not attached to `dict`s, but that's a moot point really because the only correct way is to use a `dict`, like you said. – metatoaster Jun 09 '16 at 12:02
10

I don't understand what exactly you're trying to achieve by doing this but this can be done using eval. I don't recommend using eval though. It'd be better if you tell us what you're trying to achieve finally.

>>> candy = ['a','b','c']
>>> fruit = ['d','e','f']
>>> snack = ['g','h','i']
>>> name = 'fruit'
>>> eval(name)
['d', 'e', 'f']  

EDIT

Look at the other answer by Sнаđошƒаӽ. It'll be better way to go. eval has security risk and I do not recommend its usage.

Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
2

Use a dictionary!

my_dictionary = { #Use {} to enclose your dictionary! dictionaries are key,value pairs. so for this dict 'fruit' is a key and ['d', 'e', 'f'] are values associated with the key 'fruit'
                   'fruit' : ['d','e','f'], #indentation within a dict doesn't matter as long as each item is separated by a , 
             'candy' : ['a','b','c']           ,
                      'snack' : ['g','h','i']
    }

print my_dictionary['fruit'] # how to access a dictionary.
for key in my_dictionary:
    print key #how to iterate through a dictionary, each iteration will give you the next key
    print my_dictionary[key] #you can access the value of each key like this, it is however suggested to do the following!

for key, value in my_dictionary.iteritems():
    print key, value #where key is the key and value is the value associated with key

print my_dictionary.keys() #list of keys for a dict
print my_dictionary.values() #list of values for a dict

dictionaries by default are not ordered, and this can cause problems down the line, however there are ways around this using multidimensional arrays or orderedDicts but we will save this for a later time! I hope this helps!

TheLazyScripter
  • 2,541
  • 1
  • 10
  • 19