+ 8

[ASSIGNMENT] What is the output of this code and why?

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

1st Apr 2018, 4:08 AM
Randeep Singh
Randeep Singh - avatar
5 Answers
+ 10
In the for loop : 0) In 1st iteration, n becomes 1(the first element), and a.remove(1) removes the element 1 from the list. Thus, a becomes [2,3,4,5]. 1) In 2nd iteration, n becomes second element of the list (3 in this case), and a.remove(3) removes the element 3. Thus, a becomes [2,4,5]. 2) In 3rd iteration, n becomes third element of the list (5 in this case) and the 5 gets removed. Thus a becomes [2,4]. Now, after this iteration, we reach the end of the list, and so the loop terminates. Thus, we get the output : [2,4].
1st Apr 2018, 5:17 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 5
thank you so much to all of you
1st Apr 2018, 5:28 AM
Randeep Singh
Randeep Singh - avatar
+ 4
Jan Markus It seems a.remove(n) removes the first element equal to n, and maybe that is why the output is similar in the list of strings.
1st Apr 2018, 6:13 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
2nd Apr 2018, 6:31 PM
David Müller
David Müller - avatar
- 1
Hey randeep actually i need your help plz WhatsApp me 9518294243
23rd Apr 2018, 6:42 PM
ᏕᏖᏗᏒ ᏰᎧᎩ ᏉᎥᏠᏗᏁᎴᏋᏒ
ᏕᏖᏗᏒ ᏰᎧᎩ ᏉᎥᏠᏗᏁᎴᏋᏒ - avatar