Reputation: 127
In python, Suppose I have a list:
instruments = ['apd', 'dd', 'dow', 'ecl']
How can I split these lists so that it will create:
apd[]
dd[]
dow[]
ecl[]
Thanks for the help.
Upvotes: 0
Views: 247
Reputation: 8837
You would do this:
dictionaries = {i:[] for i in instruments}
and you you would refer to each list this way:
dictionaries['apd']
dictionaries['dd']
dictionaries['dow']
dictionaries['ecl']
This is considered much better practice than actually having the lists in the current namespace, as it would both be polluting and unpythonic.
mshsayem has the method to place the lists in the current scope, but the question is, what benefits do you get from putting them in your current scope?
Standard use cases:
apd.append
eval
or locals
to get the lists, i.e. eval('apd').append
or locals()['apd'].append
Both can be satisfied using dictionaries:
dictionaries['<some name can be set programatically or using a constant>'].append
Upvotes: 3
Reputation: 18008
Try this:
instruments = ['apd', 'dd', 'dow', 'ecl']
l_dict = locals()
for i in instruments:
l_dict[i] = []
This will create apd
,dd
,dow
,ecl
lists in the local scope.
Snakes and Cofee's idea is better though.
Upvotes: 1