Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: list assignment index out of range

Tags:

python

  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

like image 523
Alex Gordon Avatar asked Nov 26 '25 16:11

Alex Gordon


2 Answers

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]
like image 188
Michael Williamson Avatar answered Nov 29 '25 05:11

Michael Williamson


Maybe you can write it like this

for row in c:
    row[:] = [x for i,x in enumerate(row) if i in keep]
like image 43
John La Rooy Avatar answered Nov 29 '25 06:11

John La Rooy



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!