12/15 purify


#1
def purify(lists):
  for i in lists:
    if i % 2 == 1:
      lists.remove(i)
  return lists

a = [1,2,3,4,5,6,7,9,11,13]
print purify(a)

it returns [2,4,6,9,13]
i seem to know what the problem is, but I can’t figure out where is wrong.
using “for” method allows you to loop through the whole list.
plz help me!


#2

lets say we have the following list:

[1,3,5]

which has the following indexes: 0, 1, 2

lists can’t have empty indexes, so when we remove value 1 from index 0:

x = [1, 3, 5]
x.remove(1)
print x

values 3 and 5 shift indexes. value 3 is now at index zero, and value 5 is now at index 1

this is the problem you are facing, by removing from the same list as you are looping over, you get this index shift, causing successive odd/uneven numbers to be skipped


#3

wow thanks a million.
now i know “why” i should use append method instead of remove.
happy new year!


#4

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