+ 3
Why does the code iterate through odd numbers only?
a = [1, 2, 3, 4, 5, 6, 7, 8] for i in a: print(i) a.remove(i) print(a) Output: 1 3 5 7 [2, 4, 6, 8]
12 Respuestas
+ 9
Kilian Andrew
a.remove(i) will remove i so then list size also get decreased.
Iterator points to next index so
Before removing an item say 1 is 0th index and 2 is in 1st index position but after removing 1, 2 goes to 0th index position.. And 1st index position value now is 3 which is value at next index to be printed.. This getting repeating till end..
Hope it helps..
+ 4
Kilian Andrew Seriously??? So you didn't check your question?
As the name says, remove() removes the item. Print the list on each iteration to see what's going on.
+ 2
Lisa I had omitted the remove function. So would you explain to me? It's followed by a.remove(i)
+ 1
Is your question is
Why does..,? Or how does...?
+ 1
Try using
a = [1, 2, 3]
for x in a:
print(x)
Output:
1
2
3
0
Did you check it in playground..?
What is your output?
it prints all numbers...
0
It prints all items.
0
Output:
1
3
5
7
Jayakrishna🇮🇳 Lisa
0
Jayakrishna🇮🇳 I had omitted the a.remove(i)
0
Thanks Jayakrishna🇮🇳
0
Lisa I get it now.