4

I have a list1 like below

list1 = ['mike', 'sam', 'paul', 'pam', 'lion']

One by one, I can specify a list name like below.

for item in list1:
     for item in line:
          mikelist = []
          mikelist.append()

for item in list1:
     for item in line:
          samlist = []
          samlist.append()

for item in list1:
     for item in line:
          paullist = []
          paullist.append()

And so forth. Instead of specifying the name in the list to create new list and append, how do I take the item from the list1 and automatically create list in that for loop line here for all the items in list1?

 for item in line:
      namefromthelist = []
      namefromthelist.append()
user10737394
  • 107
  • 1
  • 8

3 Answers3

4

Create a dictionary with the names as keys and lists as values:

dict = {}
list1 = ['mike', 'sam', 'paul', 'pam', 'lion']

for i in list1:
    dict[i] = []
print(dict)

Output:

{'mike': [], 'lion': [], 'paul': [], 'sam': [], 'pam': []}

You can then use it like this:

dict['mike'].append('blah')
print(dict['mike'])
glhr
  • 4,439
  • 1
  • 15
  • 26
0

It looks more like a job for a dictionary. Something like this will work:

names = ['mike', 'sam', 'paul', 'pam', 'lion']
persons = dict(zip(names, [[]] * len(names)))

That yields this:

>>> persons
{'mike': [], 'sam': [], 'paul': [], 'pam': [], 'lion': []}
>>>

And now you can populate each list with something like this:

fruits = ['banana', 'orange', 'apple']
for person in persons:
    persons[person].append(fruits)
accdias
  • 5,160
  • 3
  • 19
  • 31
0

I highly highly do not recommend this method and you should instead use a dictionary. However, if you insist on following down this path this is how you would achieve your desired result.

for name in list1:
    globals()['{}list'.format(name)] = [name]

print(mikelist)
# ['mike']

print(pam)
# ['pamlist']
gold_cy
  • 13,648
  • 3
  • 23
  • 45