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 ?

1
  • you are removing list item hence looping to the end will surely cause index error. Commented Apr 21, 2020 at 11:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.