0
Output of a code
I can't understand why the output of this code list = ["apple","banana","orange","mango"] for item in list: list.remove(item) print(list) is >> ['banana', 'mango'] ??? I think all of the items in the list should be deleted.
7 Antworten
+ 6
+ 6
Ebrahim Gholami honestly idk
+ 5
Ebrahim Gholami every other item in the list is removed.
+ 2
It's because the "list" size was changing during iteration. This is what happened:
First, the for loop saw the first element in "list", i.e., list[0]="apple", and removed it from "list".
At the time, "list" became ["banana", "orange", "mango"] with length 3 but the for loop itself didn't notice this, and started the next iteration.
Then, for loop searched for list[1] and got "orange" and then remove it. The "list" became ["banana", "mango"] with length 2.
Finally, the for loop wanted to search for list[2] (the third element), but noticed that "list" has only length of 2 (no third element), so it stopped.
In fact, in this code, only elements of even number index (0,2,4...) will be removed.
If you want to remove all the elements, try this:
list=["apple", "banana", "orange", "mango"]
for item in list.copy():
list.remove(item)
print(list)
+ 1
LONGTIE you're right but I want to know the reason of that .. I think for every item in the list the list.remove(item) should be applied.
+ 1
thanks LONGTIE , I get it but how we can remove all of the items with a one "for loop"?
+ 1
for some reason my playground doesnt work so I'll write here
list = ["apple","banana","orange","mango"]
for item in range(len(list)):
del list[0]
print(list)