Removing of all odd numbers from list (PURIFY)


#1
def purify(numbers):
  for i in numbers:
    if i%2 != 0:
      numbers.remove(i)
  return numbers
print (purify([1,3,5,7,9,11,15,13]))

WHAT IS WRONG WITH MY CODE


#2

remove() is a difficult approach.

lets say i have this list, with the following indexes:

4   5   5   4
0   1   2   3

the top row is the list, the bottom row the indexes.

if we then do:

.remove(5)

we get:

4   5   4
0   1   2

the 5 of index 1 got removed, but the everything to the right of the removed item shift one place to the left.

Combine this with the for loop you have, it explains why it struggles with removing successive odd/uneven numbers.

lists can’t have empty indexes, so after removing the requested item and the shifting of the elements, the loop moves on to the next index. Causing it to skip successive uneven/odd numbers.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.