Loop question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Loop question

Can anyone simplify below for loop step by step, please? lst = [0,1,2,3,4,5] n = 0 for i in lst: del lst[n] n += 1 print (i) The output is: 0 2 4

24th May 2018, 12:26 PM
Dolan
Dolan - avatar
7 Answers
+ 1
for i in lst means the following operations will be made for each existing element of lst (5 times max) 1st: we take first i = 0, delete lst[0] from lst and print i. now lst = 1,2,3,4,5, n=1 2nd: we take second element which is i=2, delete lst[1] and print i=2 now lst = 1345 n=2; 3rd we take 3rd element from lst i=4, delete lst[2] and print i=4 now lst consist of 3 elements and we cannot continue, so the loop is over
24th May 2018, 1:52 PM
Sergey Semendyaev
Sergey Semendyaev - avatar
+ 1
lst = [0,1,2,3,4,5] loop1: delete 0 print index 0 == 0 lst = [1,2,3,4,5] loop2: delete 2 print index 1 == 2 lst = [1,3,4,5] loop3: delete 4 print index 2 == 4 lst = [1,3,5] stop: no item in index 3
24th May 2018, 3:05 PM
Markus Kaleton
Markus Kaleton - avatar
+ 1
the the loop loads the list contents when it starts a loop so i is still 0 in the loop even though its 1 in the list
24th May 2018, 4:28 PM
Markus Kaleton
Markus Kaleton - avatar
+ 1
it deletes lst[0], but before that i already = lst[0] =0
24th May 2018, 4:39 PM
Sergey Semendyaev
Sergey Semendyaev - avatar
0
Markus Kaleton , In loop 1, when first it deletes 0, then print index 0, 0 is deleted, [1,2,3,4,5], so index 0 would be number 1 in NEW lst!! and n+=1 0 + 1 = 1, n=1 but we have the first output: Number 0
24th May 2018, 4:20 PM
Dolan
Dolan - avatar
0
I
30th May 2018, 11:43 AM
zahra
0
zahra what?
30th May 2018, 1:32 PM
Dolan
Dolan - avatar