-5

I have a list of variables like:

master = ['A', 'B', 'C', 'D']

I want to loop over master and create n lists where n is number of variables.

Also the names of the lists should be by the name of the elements

I tried:

for i in master:
    i = list()
    print(i)

but here the list doesn't have any name

Rahul Sharma
  • 2,187
  • 6
  • 31
  • 76

2 Answers2

0

If you want to assign a name (that is the same as the element), you probably need a dictionary.

from collections import defaultdict

master = ['A', 'B', 'C', 'D']
d = defaultdict(list)

for elem in master:
  d[elem].append(elem)

print(d["A"])  #  ["A"]

You can also do this with dict-comprehension.

d1 = {el: el for el in master}
print(d1["A"])  #  "A"

d2 = {el: [el] for el in master}
print(d2["A"])  #  ["A"]
crissal
  • 2,547
  • 7
  • 25
0

You can use python dictionaries for this . For example :

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
} 
print(thisdict)

this will print {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Please visit here for more explanations : here

Mitesh
  • 1,544
  • 3
  • 13
  • 26