+ 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]

5th May 2022, 4:47 PM
Kilian Andrew
Kilian Andrew - avatar
12 Respostas
+ 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..
5th May 2022, 5:02 PM
Jayakrishna 🇮🇳
+ 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.
5th May 2022, 5:00 PM
Lisa
Lisa - avatar
+ 2
Lisa I had omitted the remove function. So would you explain to me? It's followed by a.remove(i)
5th May 2022, 4:57 PM
Kilian Andrew
Kilian Andrew - avatar
+ 1
Is your question is Why does..,? Or how does...?
5th May 2022, 4:55 PM
Jayakrishna 🇮🇳
+ 1
Try using a = [1, 2, 3] for x in a: print(x) Output: 1 2 3
7th May 2022, 4:49 PM
Iftekhar Ahmmed
0
Did you check it in playground..? What is your output? it prints all numbers...
5th May 2022, 4:50 PM
Jayakrishna 🇮🇳
0
It prints all items.
5th May 2022, 4:50 PM
Lisa
Lisa - avatar
0
Output: 1 3 5 7 Jayakrishna🇮🇳 Lisa
5th May 2022, 4:53 PM
Kilian Andrew
Kilian Andrew - avatar
0
Jayakrishna🇮🇳 I had omitted the a.remove(i)
5th May 2022, 4:59 PM
Kilian Andrew
Kilian Andrew - avatar
5th May 2022, 5:06 PM
Kilian Andrew
Kilian Andrew - avatar
0
Lisa I get it now.
5th May 2022, 5:08 PM
Kilian Andrew
Kilian Andrew - avatar