Why does my loop skip indexes of my list?

why does the loop skips 8 goes directly to 12(the element) and removes it?

When iterating a list we must keep in mind the effect of removing an element. If the element at the current position is removed, those to the right of it shift over to fill the vacancy, thus shortening the list, but also skipping the element that slid into the current position (which position has already been evaluated). The next element in the loop is two over from the one that was removed.

2 Likes


One of the condition in my while loop is len(lst) > 0 then how can we have [4,8,10] as empty list? If that condition is to have at least one element

If you mean that the return value is an empty list, then given all even numbers in the input one would expect just that. An empty list. The list has depleted itself of elements and is now length 0, failing one of the conditions in the while loop.

1 Like