8

I have a list of strings such as:

names = ['apple','orange','banana'] 

And I would like to create a list for each element in the list, that would be named exactly as the string:

apple = []  
orange = []  
banana = []  

How can I do that in Python?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
user1962851
  • 115
  • 1
  • 5
  • 6
    What is your end goal? I ask because you can usually accomplish what you want without having to name numerous variables in that way. – RocketDonkey Jan 09 '13 at 15:57
  • @DSM could you explain why you vote that this and [this](http://stackoverflow.com/q/24937068/674039) are not dupes? thanks! – wim Aug 12 '14 at 21:13
  • @wim: sure! This one came a year and a half before. If you want to close the other one as a dup of this, or both of them as a dup of some earlier one, that might make sense. But since the One True Answer is the same in both, I can't see how this question is a duplicate of the other one. – DSM Aug 12 '14 at 21:21
  • @DSM I didn't bother to check the dates, maybe I should have (?). We are discussing this on [meta](http://meta.stackoverflow.com/q/268558/674039). – wim Aug 12 '14 at 21:55

2 Answers2

32

You would do this by creating a dict:

fruits = {k:[] for k in names}

Then access each by (for eg:) fruits['apple'] - you do not want to go down the road of separate variables!

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
6

Always use Jon Clements' answer.


globals() returns the dictionary backing the global namespace, at which point you can treat it like any other dictionary. You should not do this. It leads to pollution of the namespace, can override existing variables, and makes it more difficult to debug issues resulting from this.

for name in names:
    globals().setdefault(name, [])
apple.append('red')
print(apple)  # prints ['red']

You would have to know beforehand that the list contained 'apple' in order to refer to the variable 'apple' later on, at which point you could have defined the variable normally. So this is not useful in practice. Given that Jon's answer also produces a dictionary, there's no upside to using globals.

Community
  • 1
  • 1
root
  • 76,608
  • 25
  • 108
  • 120
  • Actually I prefer this solution more because it allows me to create lists instead of a dictionary as suggested. So I would like to ask why should I rather use @Jon Clements methods instead of this one? Thank you very much to both of you! – user1962851 Jan 10 '13 at 10:10
  • 1
    @user1962851 -- `globals()` is pretty much a dictionary that holds global variables. This solution can lead to unwanted pollution of the global namespace and to the overriding existing variables. If you use Jon's solution you can get the same lists by using `fruits['apple']` and similar, so there isn't much of a downside to it. – root Jan 10 '13 at 10:22
  • Ok, thank you very much for your explanation. I am gonna set Jon's answer as the accepted one then. – user1962851 Jan 10 '13 at 10:50