Purify (Why does removing not work,while appending work)


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/purify?action=lesson_resume&link_content_target=interstitial_undefined

<In what way does your code behave incorrectly? Include ALL error messages.>
Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4].
Run

<What do you expect to happen instead?>
i expected it to be correct XDD. Well, i roughly get what the error is trying is trying to say,but i dont understand why…the codes make sense to me…I hope someone can explain it to me because these have been bothering me so many times…Thanks

```python

def purify(numbers):
for number in numbers:
if number%2!=0:
numbers.remove(number)
return numbers

<do not remove the three backticks above>

#2

Hi @corerockstar75711,

Removing items from the object that you are traversing interferes with the traversal process, and can give erroneous results. It is best to create a new object, place the appropriate items there, and finally return that new object. That maintains the integrity of the traversal of the original object.


#3

oh ok thank you :grin::grin:


#4

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