1

I am tryin to delete an item from a list by specifying the index of the list I want to delete but I get an error.

My code:

tuu = [1,2,3,4,'nan', 8]

for i in range(len(tuu)):
    if tuu[i] == 'nan':
        del tuu[i]

but I get the error:

      7 for i in range(len(tuu)):
----> 8     if tuu[i] == 'nan':
      9         del tuu[i]

IndexError: list index out of range 
piccolo
  • 2,093
  • 3
  • 24
  • 56
  • Try the remove method. – Elan Mar 11 '16 at 10:34
  • `[i for i in lst if i != 'nan']` – Avinash Raj Mar 11 '16 at 10:34
  • When you want to remove item in a for loop using `range(len(list))` while iterating, you should remove it the [reverse way](http://stackoverflow.com/questions/35618307/how-to-transform-string-into-dict/35618686#35618686) (check the link) – Ian Mar 11 '16 at 10:34
  • It's also possible to assign in-place without creating a new list using slice notation: `tuu[:] = [x for x in tuu if x != 'nan']` – mhawke Mar 11 '16 at 10:41

1 Answers1

2

When you use a for loop, Python will call __iter__ on the iterable you are looping over. __iter__ will return an iterator object which keeps track of where you are currently in your iterable.

If you modify the length of your iterable (the list) while looping over it, the iterator will get confused.

After deleting tuu[i] your list has one less element, but the iterator won't know and tries to access the previously last index -> that's where you get an IndexError.

The canonical way to filter a list in Python is to build a new list and reassign the name of the old list:

>>> tuu = [1, 2, 3, 4, 'nan', 8]
>>> tuu = [x for x in tuu if x != 'nan']
>>> tuu
[1, 2, 3, 4, 8]
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • In this case, `tuu[5]` was deleted. If one wanted to remove an element of the same index in another list, how would one go about it? In other words, how can one find the index of the removed elements from the first list and remove the elements of the same index from the second list? –  Apr 24 '17 at 04:31