Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Creating a number of lists depending on the count

Tags:

python

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
like image 943
Harpal Avatar asked Mar 17 '26 20:03

Harpal


2 Answers

This is my interpretation of what you want, I hope I guessed it right (you weren't very clear).

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

Now you can use it like this:

headers[1].append("this goes in the first header")
headers[2].append("this goes in the second header")
like image 72
orlp Avatar answered Mar 19 '26 09:03

orlp


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)
like image 26
vz0 Avatar answered Mar 19 '26 09:03

vz0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!