0

I get:

if(lst[i]%2!=0):

IndexError: list index out of range

from this code:

lst=[1,2,3,4,5,6]
for i in range(len(lst)):
    if(lst[i]%2!=0):
        lst.remove(lst[i])
print(lst)

I am trying to print only the even numbers in a list and I do not see a problem with my code why am I getting this error ?

ygtmnv
  • 37
  • 5

2 Answers2

2

You should not remove from a list while iterating it. Use, for instance, a list comprehension and slice assignment to achieve the same modification:

lst = [1,2,3,4,5,6]

lst[:] = [x for x in lst if x % 2 == 0]
# or simply (if you don't need to mutate the original list) 
# lst = [x for x in lst if x % 2 == 0]

print(lst)
# [2, 4, 6]

This has also better time complexity (linear) whereas the repeated remove approach is quadratic.

user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Instead of removing the item from the original list, you can also split the original list into 2 new lists, evens and odds

lst=[1,2,3,4,5,6]
evens = []
odds = []
for i in lst):
    if(i % 2 != 0):
        odds.append(i)
    else:
        evens.append(i)

print(evens)
Lambo
  • 1,094
  • 11
  • 18