12/15 purify


#1
def purify(batshit):
  for i in range(0,len(batshit)):
    if batshit[i] % 2 == 1:
      batshit.pop(i)
  return batshit

a = [1,2,3,4,5,6,5,5,5,5]
print purify(a)

can you guys tell me what’s wrong with my code?
it says “list index out of range”


#2

the length of [1,2,3,4,5,6,5,5,5,5] is 10, so the the loop will make 10 iterations. But by removing items from the list you are looping over, the list will shorten while the loop still wants to make 10 iterations, this results in an index error

removing using .pop() or any other method is a very difficult approach to solve this problem


#3

I’d also like to note that the instructions for this exercise state:

Do not directly modify the list you are given as input; instead, return a new list with only the even numbers.

So I guess this isn’t a problem that you need to worry about.


#4

Well, the pop() method is giving you problems here. Also you are modifying the original list that is been passed as argument.
You can fix your code by creating a new empty list that will store the even numbers. In your for loop, if you find an even number use .append() to store every even number to your empty list.
Return your new list, not the original.


#5

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