How can I create lists from a list of strings?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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!

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x