Delete Starting Even Numbers - Python

Hello - I’m currently doing the code challenge for the loops (3. Delete Starting Even Numbers). I understand the solution but also trying to figure out if I can use a for loop to solve this problem. Specifically, I’m trying to understand why this isn’t working…

lst = [4, 8, 10, 11, 12, 15]
for x in lst:
if x % 2 == 0:
lst.remove(x)
else:
break
print(lst)

Instruction:
Write a function called delete_starting_evens() that has a parameter named lst .

The function should remove elements from the front of lst until the front of the list is not even. The function should then return lst .

Modifying the same object you’re iterating through is almost always a mistake, it’s very hard to keep track of such operations. In this example you risk skipping elements since the effective index of each element is liable to change when you remove earlier elements.

Thank you for your quick response. Actually, I figured out a potential solution by creating a new list or at least this worked. Still learning :slight_smile:

new_list =
for x in range(len(lst)):
if lst[ x ] % 2 == 0:
continue
else:
new_list = lst[x:]
break
return new_list

1 Like