Dan Smith
Dan Smith

Reputation: 43

Python: list inside a list index out of range error

I'm getting an error when trying to append values to a list inside of a list. What am I doing wrong?

xRange = 4
yRange = 3
baseList = []
values = []
count = 0

#make a list of 100 values
for i in range(100):
    values.append(i)

#add 4 lists to base list
for x in range(xRange):
    baseList.append([])
#at this point i have [[], [], [], []]

#add 3 values to all 4 lists
    for x in range(xRange):
        for y in range(yRange):
            baseList[x][y].append(values[count])
            count += 1

print baseList

#the result i'm expecting is:
#[[0,1,2], [3,4,5], [6,7,8], [9,10,11]]

I'm getting this error:

Traceback (most recent call last):
  File "test.py", line 19, in <module>
    baseList[x][y].append(values[count])
IndexError: list index out of range

Upvotes: 3

Views: 3512

Answers (2)

poke
poke

Reputation: 387775

for x in range(xRange):
    baseList.append([])
# at this point i have [[], [], [], []]

Right, baseList = [[], [], [], []]. As such, accessing baseList[0][0] will fail as the first sublist has no elements.

Btw. you can get the wanted list a lot easier using some itertools and recipes.

>>> x = 4
>>> y = 3
>>> list(itertools.islice(zip(*([itertools.count()] * y)), x))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]

This is basically an x-take of an y-grouper of an indefinite count starting at 0.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838376

You shouldn't index into an empty list. You should call append on the list itself.

Change this:

baseList[x][y].append(values[count])

To this:

baseList[x].append(values[count])

Result:

[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]

See it working online: ideone

Upvotes: 5

Related Questions