Error in program for removing even numbers in a list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Error in program for removing even numbers in a list

The code I've typed is this:- l=eval(input("list:")) for i in range(0,len(l)): if l[i]%2==0: l.pop(i) print(l) It seems right to me but I'm getting an IndexError PLEASE HELP

14th May 2020, 7:11 AM
Sriya
3 Answers
+ 4
Code Crasher, what Sriya in the code is doing, is to collect an input from user. l=eval(input("list")) takes a sequence that the user enters (like: 1,2,6,3,0,8). By using eval() this input will be converted to a tuple automatically. But tuple is imutable. So it would be better to convert tuple to a list: l=list(eval(input("list")))
14th May 2020, 10:48 AM
Lothar
Lothar - avatar
+ 2
The problem in this code is, that during a loop iteration elements are deleted with pop. You are running a for loop controlled by a range object. If you are forced by some reasons to use the original list, a while loop can solve the problem. Use a counter that starts at the end of the list and decrement the index counter by 1 in each iteration. So you should think about a solution, that works even when elements are deleted. An appropriate way of doing such a task could also be to create a new list, containing only odd numbers. This can be done with a for loop, a comprehension or a filter function.
14th May 2020, 8:32 AM
Lothar
Lothar - avatar
+ 2
Thank you Lothar!
14th May 2020, 12:17 PM
Sriya