+ 1

Python odd number help

I dont understand why my code is not working, its outputting nothing. I have a task to delete all the odd numbers in a list, and i made a script. For some reason its not outputting anything. The ‘idk’ variable was a try to indent the code because i for some reason though it would work. Any coding genius that can help me? Code: https://code.sololearn.com/clU3NSA8nin2/?ref=app

29th Jul 2023, 12:28 PM
David Kobbersmed
David Kobbersmed - avatar
2 Respostas
+ 4
as Lisa already mentioned: this code in the second while loop is causing an issue: (infinite loop) while lengthIndex < length: if nums[lengthIndex] in oddNumbers: .... > lengthindex, length and nums[lengthindex] are never changing, which causes the loop to be infinite. general: > the removing of elements from a list during an iteration causes problems with the indexes when starting to iterate from left to right in the list. > if we are using a reverse iteration from right to left, the issue will not occur. > i would recommend you to re-think the code. are you really forced to remove elements from a list, or is it allowed to create a new list base on the initial list and a condition that defines that only even numbers go to the new list? > if the task is to really remove the odd numbers *inplace* without using an additional list, you can read more about this here: https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating
29th Jul 2023, 7:06 PM
Lothar
Lothar - avatar
+ 3
in the while-loop (line 14) you are change the length of the list that you are iterating. supposed you have [1, 2, 3] you start at index = 0 and remove the element 1: [2, 3]. then you increase the index, so index = 1. now what is the element at index 1?
29th Jul 2023, 1:01 PM
Lisa
Lisa - avatar