Reputation: 1
Consider, I have a list
subjects = ['subject1', 'subject2', 'subject3', 'subject4', 'subject5']
How do I convert these individual list elements to individual lists?
subject1 = [ ]
subject2 = [ ]
subject3 = [ ]
subject4 = [ ]
subject5 = [ ]
Upvotes: 0
Views: 74
Reputation: 2190
subjects = ['subject1', 'subject2', 'subject3', 'subject4', 'subject5']
ret = {}.fromkeys(subjects, [])
Then ret
is
{'subject1': [], 'subject2': [], 'subject3': [], 'subject4': [], 'subject5': []}
-- EDIT --
As @Anand said, all the values are the same list reference. To avoid this, there's a workaround:
ret = {k: [] for k in subjects}
Upvotes: 4
Reputation: 391
If you really want induvidual lists, and not a dictionary:
for subject in subjects:
exec(subject + " = list()")
Upvotes: 0
Reputation: 8101
If you use dictionnary, you can do the following :
dictionnary = dict((s, []) for s in subjects)
You can access your list by doing the following :
my_list = dictionnary['subject1']
my_list.append(5)
print(dictionnary['subject1'] == [5]) # True
# Or also
dictionnary['subject1'].append(5)
Upvotes: 0