How can I create lists from a list of strings? [duplicate]

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!


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.