joechoj
joechoj

Reputation: 1409

Create many new lists, to be populated from loop

What is the best way to generate empty, named lists? Do they need to be created manually? I had hoped the following would work:

fieldlist = ['A', 'B', 'C']

for fieldname in fieldlist:
    str(fieldname) + 'list' = []

Actual result:

  File "<interactive input>", line 2
SyntaxError: can't assign to operator

Desired result:

Alist = []
Blist = []
Clist = []

Upvotes: 0

Views: 59

Answers (2)

Sphinx
Sphinx

Reputation: 10729

Using globals. Also you could try locals(), vars(), then check this URL to understand the differences.

PS: Thanks the corrections from @ShadowRanger.

As API defined:

globals()

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

The codes will be like below if using globals():

fieldlist = ['A', 'B', 'C']

for fieldname in fieldlist:
    name=str(fieldname) + 'list'
    globals()[name]=[]
print (Alist, Blist, Clist)

Output:

[] [] []
[Finished in 0.179s]

Upvotes: -1

jpp
jpp

Reputation: 164673

Use a dictionary. There is rarely, if ever, a need to dynamically name variables from strings.

fieldlist = ['A', 'B', 'C']

d = {}

for fieldname in fieldlist:
    d[str(fieldname) + 'list'] = []

# {'Alist': [], 'Blist': [], 'Clist': []}

Upvotes: 2

Related Questions