0

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 = []
Sphinx
  • 10,519
  • 2
  • 27
  • 45
joechoj
  • 1,339
  • 10
  • 12

2 Answers2

2

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': []}
jpp
  • 159,742
  • 34
  • 281
  • 339
  • As I'm using numpy to do calculations with & on the arrays, I'd like to have them as standalone lists, and am pretty unused to working with dicts. Can I create them using a dict and then use dynamic assignment statements to split them out? Or perhaps it's best just to create them explicity, even if it's cumbersome? – joechoj Feb 21 '18 at 06:52
-1

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]
Sphinx
  • 10,519
  • 2
  • 27
  • 45
  • Modifications to the `locals()` dictionary [are explicitly documented as being a bad idea](https://docs.python.org/3/library/functions.html#locals); there is no guarantee that the modifications actually work. And in fact, it would not work in the general case on modern Python; the only reason it works here is because you did it at global scope, where `locals()` returns the same `dict` that `globals()` returns (and module globals really are stored in a mutable `dict`, so changing it works); inside a function body, the `dict` returned by `locals()` can't be mutated to do anything useful. – ShadowRanger Feb 15 '18 at 02:16