+ 3
remove() function iteration problem in python to remove odd/even numbers from list
CODE link: https://code.sololearn.com/c20HpGq6yw2Q/?ref=app problem: remove function when used in iteration remove only consecutive odd/even numbers (not all)) Please do comment if you got/have idea about this
6 Respuestas
+ 6
It is because when an element is removed, the next element will be skipped in the next iteration because it follows the index order of elements.
Although there is a way to solve this by iterating the index instead of element. Then increment a variable then subtract the index by that variable, so the loop will still follow the index order of the list.
See this for example:
https://code.sololearn.com/cjAv4915AOdQ/?ref=app
+ 5
There is not a problem with it but you are actually modifying original list , so when list encounters first even number, the loop count is at 2 nd element but then using remove method list is reduced to [1,2,2,2,3,5,7]
and during next iteration the count loop should be at 3rd element i. e. It will skip the number 2 which is 2nd element.
+ 5
This is a common problem when using remove() or pop() or del() during iteration.
Your list is going to change shape as it has index items removed during the process, but the iteration count will continue causing the code to skip over certain items
Example below
lst = [2,4,6]
for i in lst:
if i%2==0:
lst.remove(i)
print(lst) #[4]
+ 3
Harshit Jawla
During iteration you can't remove even value because everytime index will change. Remove method remove elements on index based so it is not possible.
2nd way is add odd items in another list.
+ 3
Thanks to all. I got it.
I was searching for it from much time
+ 3
Harshit Jawla
You can do like this
l = [1, 2, 2, 2, 2, 3, 5, 7]
l1 = []
for i in l:
if i % 2 == 1:
l1.append(i)
print(l1)