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.

9th Jul 2018, 10:23 PM
Ebrahim Gholami
Ebrahim Gholami - avatar
7 Antworten
9th Jul 2018, 10:53 PM
LONGTIE👔
LONGTIE👔 - avatar
+ 6
Ebrahim Gholami honestly idk
9th Jul 2018, 11:01 PM
LONGTIE👔
LONGTIE👔 - avatar
+ 5
Ebrahim Gholami every other item in the list is removed.
9th Jul 2018, 10:45 PM
LONGTIE👔
LONGTIE👔 - avatar
+ 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)
11th Jul 2018, 12:09 PM
李立威
+ 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.
9th Jul 2018, 10:49 PM
Ebrahim Gholami
Ebrahim Gholami - avatar
+ 1
thanks LONGTIE , I get it but how we can remove all of the items with a one "for loop"?
9th Jul 2018, 10:56 PM
Ebrahim Gholami
Ebrahim Gholami - avatar
+ 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)
10th Jul 2018, 6:03 AM
Markus Kaleton
Markus Kaleton - avatar