0
Why doesn’t this work?
Why doesn’t this code remove 993 from the following string? 0 42 64 77 993 numLst = list(map(lambda i: int(i), input().split())) for i in numLst: if i % 2 != 0: numLst.remove(i) numLstStr = list(map(lambda i: str(i), numLst)) space = " " print(space.join(numLstStr)) https://code.sololearn.com/c500OFQKR36o/?ref=app
5 ответов
+ 8
Brave Tea , there is no "normal" for loop or "foreach" loop. There is only the genuine python for loop. As Rik already mentioned, the issue happens when deleting elements during a loop.
I suppose your code should give a list with only even numbers - ?
There are several strategies to avoid the index problem:
(1) starting iteration from the end of iterable
...
for i in numLst[::-1]:
...
(2) using a comprehension instead of deleting elements:
print([i for i in input().split() if int(i) % 2 == 0])
+ 7
When iterating through the list, you are removing the lst[i] if the condition is met.
This causes the next number to take the position of the removed number, but the iteration moves on.
Your example has 2 odd numbers at the end of the list.
When 77 is removed, 993 takes it's place.
The iteration moves on to discover the end of the list without examining 993.
Welcome back Brave Tea
+ 6
When you run a for loop, the for loop calls iter on your iterable.
So an iterator is made. Then it's dishing out the elements by index, assigning them to your loop variable, until it reaches the end. Then it raises StopIteration.
The iterator is created once at the beginning on the loop. It doesn't know or care if your list gets changed within the loop, it strictly returns l[0], l[1], l[2]...
So when you erase an element in the loop, it's as if you walk on a running escalator.
You're basically pulling out the list from under the iterator.
Run this for a demonstration:
l = [1, 2, 3, 4, 5]
for i in l:
l.remove(i)
print(l)
+ 5
I think so, yes.
+ 3
Rik Wittkopp firstly: thank you :)
second, I know that to be the case with a “normal” for loop, but this is basically a foreach loop, right? Probably just a for loop beneath the surface then :)