1

I need to removes all odd numbers in the list, and returns the result.

For example, purify([1,2,3]) should return [2]

My function is

def purify(num):

for x in num:
    if x%2 != 0:
        num.remove(x)    

return num

So for purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4].

John Constantine
  • 838
  • 2
  • 11
  • 29

3 Answers3

2

If let me do this function, my answer is this:

def purify(n):
    new_array = []
    for index in range(0, len(n)):
        if n[index] % 2 != 0:
            new_array.append(n[index])
    return new_array

a = [4,5,5,4]
print purify(a)

Next let me explain your code why it happens error.

When your for loop scan each element, the workflow is like this:

  1. first step when loop scan first index

     v
    [4,5,5,4]
    
  2. second step when loop scan second index. Because it satisfy the if-else condition, the second index is removed , the third and forth index font shift a index.

       v
    [4,5,5,4]
    
  3. third step when loop scan third index.

         v
    [4,5,4]
    

result: [4,5,4]

That's why. The 5 element loses to be scanned.

  • 1
    This answer clearly explains for python beginner. Compared with abstruse theory, I like straightforward tutorial. – Burger King Mar 22 '15 at 02:42
1

You lose/invalidate the reference to the list when you call remove.

One way of achieving the same behavior is to create a new list.

def purify(old_list):
    new_list = []
    for x in old_list:
        if x % 2 == 0:
            new_list.append(x)
    return new_list

Or you can also do a list comprehension to express this in a more Pythonic fashion.

def purify(old_list):
    return [for x in old_list if x % 2 == 0]
0

Use a list comprehension. It's what they are designed for. From the docs:

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

>>> L = [1,2,3,4,5]
>>> [x for x in L if x%2==0]
[2, 4]
>>> L = [4,5,5,4]
>>> [x for x in L if x%2==0]
[4, 4]

As a function:

>>> def purify(nums):
...     return [x for x in nums if x%2==0]
...
>>> purify([4,5,5,4])
[4, 4]
Mark Tolonen
  • 132,868
  • 21
  • 152
  • 208