- 1

Pls explain this piece of code

st=[i for i in range(6)] print(st) for i in st: st.remove(i) print(st) print(sum(st))

26th Oct 2019, 4:18 PM
Thakur Lion😎😎
Thakur Lion😎😎 - avatar
1 Resposta
+ 1
When you iterate over a list, the first loop uses the first element of the list, the second loop uses the second element, third loop uses the third element and so on... When you remove an element from the list you are iterating on, it changes it. Your list starts off as [0,1,2,3,4,5], but your first loop removes the first element, making the list [1,2,3,4,5]. Now the second loop uses the second element which is now 2. 2 gets removed and, in the same way, 4 is removed in the third loop. List ends up as [1,3,5]. That's why the sum at the end is 9.
26th Oct 2019, 5:08 PM
Russ
Russ - avatar