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?

4
  • 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. Commented Jan 9, 2013 at 15:57
  • @DSM could you explain why you vote that this and this are not dupes? thanks! Commented Aug 12, 2014 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. Commented Aug 12, 2014 at 21:21
  • @DSM I didn't bother to check the dates, maybe I should have (?). We are discussing this on meta. Commented Aug 12, 2014 at 21:55

2 Answers 2

33

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!

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

Comments

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.

3 Comments

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 -- 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.
Ok, thank you very much for your explanation. I am gonna set Jon's answer as the accepted one then.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.