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?
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.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
.You would do this by creating a
dict
:Then access each by (for eg:)
fruits['apple']
- you do not want to go down the road of separate variables!