+ 2

Python challenge question

Why this code doesn't remove all the items from the list? a=[1,2,3,4,5] for x in a: a.remove(x) print(a) When i run this i get [2,4] instead of an empty list but i just don't get it why 2 and 4 are left. When i do this a=[1,2,3,4,5] for x in a: print(x) then the output is 1 2 3 4 5 so x can take all these values but still the list is not getting empty???? Damn confusing!!!

15th Jun 2019, 7:52 PM
Rishu Kumar
Rishu Kumar - avatar
7 Answers
+ 6
The problem for this behaviour is really simple. Let's go through step by step or in other words iteration for iteration. you started with: a=[1,2,3,4,5] for x in a a.remove(x) print(a) 1. iteration: for loop gives you index 0 from a => "1" then you remove(x) = "1" from list a list a is now [2,3,4,5] 2. iteration: for loop gives you now index 1 from a => "3" then you remove 3 from the list a list a is now [2,4,5] 3. iteration: for loop gives you now index 2 from a => "5" then you remove 5 from the list a list a is now [2,4] As there are no more elements iteration stops here. To get rid of this problem you have to start iteration from the end of the list with: [::-1]. This code is doing this: a=[1,2,3,4,5] for x in a[::-1]: a.remove(x) print(a) https://code.sololearn.com/cQGiLQHt6TEL/?ref=app
15th Jun 2019, 8:41 PM
Lothar
Lothar - avatar
+ 3
Because there is an invisible counter in "for x in a" it counts from 0 "i = 0", in each iteration it gets incremented by 1 "i += 1" and gives variable a new value "x = a[i]". It repeates this, until there are no values at "a[i]", because at the third iteration "i = 3" and "a = [2, 4], there are no values at "a[i]" = "a[3]", for loop is broken. >>>a = [1, 2, 3, 4, 5] >>>for x in a: ... a.remove(x) ... print(a) ... [2, 3, 4, 5] [2, 4, 5] [2, 4] >>>print(a) [2, 4]
15th Jun 2019, 8:15 PM
Seb TheS
Seb TheS - avatar
+ 3
Lothar and Seb TheS thanks a lot for the explanation 👍
15th Jun 2019, 10:34 PM
Rishu Kumar
Rishu Kumar - avatar
+ 1
Excel why x=odd?
15th Jun 2019, 7:58 PM
Rishu Kumar
Rishu Kumar - avatar
+ 1
Excel I don't understand what u r saying. Can u please explain
15th Jun 2019, 8:12 PM
Rishu Kumar
Rishu Kumar - avatar
0
X=odd
15th Jun 2019, 7:53 PM
Excel
Excel - avatar
0
No item was assigned to remove. So odd or random
15th Jun 2019, 8:03 PM
Excel
Excel - avatar