Skip to content
Advertisement

python: list assignment index out of range

  for row in c:
    for i in range(len(row)):
      if i not in keep:
        del row[i]

i am getting this error on the last line:

IndexError: list assignment index out of range

i dont understand how it can be out of range if it exists! please help

Advertisement

Answer

If row is a list, then don’t forget that deleting an element of a list will move all following elements back one place to fill the gap, so all of the later indices into the list will be off-by-one (and each time you delete another element, the error in each index grows by one). There are a few ways to avoid this problem — to give one, try iterating through the list backwards.

To respond to how to iterate backwards, you could try using the extra parameters you can pass to range. The first two parameters give the range to iterate over (the lower bound being inclusive, and the upper bound exclusive), and the third parameter is the step:

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(0, 5)
[0, 1, 2, 3, 4]
>>> range(3, 5)
[3, 4]
>>> range(3, 5, -1)
[]
>>> range(5, 3, -1)
[5, 4]

So, in your case, it seems you’d want:

range(len(row) - 1, -1, -1)

Or the easier to read (thanks to viraptor):

reversed(range(len(row))

Alternatively, you could try using list comprehensions (I’m assuming c is a list):

for row_number, row in enumerate(c):
    c[row_number] = [x for i, x in enumerate(row) if i in keep]

Advertisement