0

Doubt

Anyone know answer? The following code removes all the items from the list? a = [1, 2, 3, 4, 5] for n in a: a.remove(n) print(a) Answer is False: Can you explain how it is?

4th Apr 2020, 1:13 PM
Gokul krishnan
Gokul krishnan - avatar
2 Respuestas
+ 4
The loop walks over the list, like element 0, 1, 2... until it's over. If you erase an element, while you loop over it, the element that was 1 before, will become 0, and element 2 will become 1. Effectively, you are missing a step each time, because the list moves under your feet like an escalator. You end up removing only every second element
4th Apr 2020, 1:21 PM
HonFu
HonFu - avatar
+ 2
Thank you Honfu bro 😎
4th Apr 2020, 1:26 PM
Gokul krishnan
Gokul krishnan - avatar