'Python: Creating a number of lists depending on the count

Im trying to create a number of lists depending on the number in my header_count. The code below should generate 3 lists but i get a syntax error instead.

header_count = 4
for i in range(1, header_count):
    header_%s = [] % i


Solution 1:[1]

What you want is to to create a list of lists:

header_count = 4
header = []
for i in range(header_count):
    header[i] = []

In the header variable references a list containing 4 lists. Each list can be accessed as follow:

header[0].append(1)
header[1].append("Hi")
header[2].append(3.14)
header[3].append(True)

Solution 2:[2]

If you need list names (as it seems from your comment to nightcracker answer), you can use a dictionary of lists:

header_count = 4
listDict = {}
for i in range(1, header_count):
    listDict["header_"+str(i)] = []

Then you can access the dictionary using header_1, header_2, header_3 as keys.

Solution 3:[3]

What did you mean by header_%s? % is the mod operator, of course you can't assign to an expression involving an operator. It's like writing

a+b = c

You can't assign to a+b, nor can you assign to header_%s.

Did you mean this?

header_lists = [[] for i in range(1,header_count)]

Solution 4:[4]

You can use global() to create these variables:

header_count = 4
for i in range(1, header_count):
    globals()[f"header_{i}"] = []

Note: you started your range with value 1, so you will create three empty lists:

header_1
header_2
header_3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Vincenzo Pii
Solution 3 Ilya Kogan
Solution 4 Rodolfo Bugarin