purified = sequence doesn't create a copy of sequence and assign to purified, rather both variables point to the same object, which you are trying to do. In addition, you are also modifying the same list you are iterating on, hence the weird behavior.
You have a few choices, and all of them work on Python 2.7
- Make a copy of sequence via
sequence[:] called list splicing, and iterate on it
def purify(sequence):
#Iterate on copy of sequence
for i in sequence[:]:
if i % 2 != 0:
sequence.remove(i)
return sequence
print purify([4, 5, 5, 4])
#[4, 4]
- Use list-comprehension to only pick even values from the list
def purify(sequence):
#Pick only even values
return [item for item in sequence if item%2 == 0]
print purify([4, 5, 5, 4])
#[4, 4]
- Use
filter to filter out odd values
def purify(sequence):
# Iterate on copy of sequence
return list(filter(lambda x:x%2==0, sequence))
print(purify([4, 5, 5, 4]))
# [4, 4]