+ 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
5 Réponses
+ 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")))
+ 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.
+ 2
Thank you Lothar!