Python Introduction


Could someone please help me debug this code? I’m trying to create a function that removes all odd numbers from a list. Thank you!

def purify(numbers):
for each in numbers:
if each % 2 != 0:
return numbers


Looking at your code, it doesn’t look like there’s anything wrong with the function definition… but just to be sure, I ran it.

If I pass your function a list of numbers, it runs properly and only returns the even numbers from the list I gave it as input.

If you’re getting an error, I suspect it’ll be related to what you’re providing your function as input. (I’m assuming that your code is correctly indented when you’re running it, and you’ve just not pasted it as a codeblock on the forum.)

If you can post the list that you’re passing to your purify function, as well as the error message you’re getting from Python, we can probably help you fix it. :slight_smile:


@thepitycoder, have you tried running with successive odd numbers, for example:


it will not work correctly, due to index shift. The moment a item gets removed from the list, everything to the right of the removed item shifts one spot to left (lists can’t have empty indexes), and the loop proceed to the next index


I used a particularly unimaginative series of integers to test that there were no glaringly obvious issues I didn’t spot by reading the code over, the grey matter isn’t on top form this evening it seems.

I wasn’t entirely wrong, though - I did say the issue would be related to the input the function was being given! :wink:


@thetwodl, using .remove() is not advised, it makes this challenge even more challenging.