Please who can explain why this doesn't remove every item in the list. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Please who can explain why this doesn't remove every item in the list.

List = [i for i in range(8)] for i in List: List.remove(i) Print(List)

30th Aug 2022, 2:09 PM
Shabach
Shabach - avatar
3 Answers
+ 6
when you remove, list size is gets decreased so the next value is, not what you expected value as of without remove. See ex: list is [2,3,4] then if you remove 2, (its at index 0) , then list is [3,4 ] and next value is at index 1 is 4. Not 3 hope it helps.
30th Aug 2022, 2:17 PM
Jayakrishna 🇮🇳
+ 4
Jayakrishna🇮🇳 thank you so much. I understand it now.
30th Aug 2022, 2:32 PM
Shabach
Shabach - avatar
+ 4
List.remove(List[0]) this is a 2nd alternative to Lothar s solution. while list: list.pop(0)
30th Aug 2022, 2:53 PM
Oma Falk
Oma Falk - avatar