+ 4

Python - Who can explain me this sequence?

a = [1,2,3,4,5] for n in a: a.remove(n) print (a) print (a)

4th Apr 2020, 8:01 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
5 Answers
+ 7
As Ramin.RX7 stated, the remove function is removing n on each iteration. a = [1,2,3,4,5] n:0 = a[0] which is 1 1 is removed a = [2,3,4,5] n:1 = a[1] which is now 3 3 is removed a = [2,4,5] n:3 = a[3] which is now 5 5 is removed print(a) [2, 4]
4th Apr 2020, 9:16 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 4
Line 2: select all members of a and name them n Line 3: remove n from a Line 4: print a every time we remove a member Line 5: at the end we print a and there is nothing in it.
4th Apr 2020, 8:08 AM
Ramin.RX7
Ramin.RX7 - avatar
+ 4
Paolo De Nictolis Not that surprising...: On the first round of Iteration you remove the 1. element 1(with index 0). Python prints [2,3,4,5] Now 2 is the first element in the list (index 0). The second round of iteration starts and n takes care of the second element in the list which is 3 (index 1) and removes it. Then the third element 5(now Index 2) is removed. After that No more elements with Index>2 are left. The list hast two elements now... 2 and 4... a=[2,4]
4th Apr 2020, 9:38 AM
Crash
Crash - avatar
+ 3
Ramin.RX7 execute this code and... SURPRISE! Result is [2,4]!
4th Apr 2020, 8:17 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
+ 3
removing during iteration leads to computable but for humans normally surprising results.
4th Apr 2020, 8:26 AM
Oma Falk
Oma Falk - avatar