Alok
Alok

Reputation: 8978

Remove odd numbers from a list

I have a general doubt since my logic seems correct but still it gives me the wrong result. I need to understand, why this logic doesn't work smoothly.

Question is simple, please do not judge me on this basis, plus I'm new to python. So here is the question

To remove odd numbers from the provided list

My Code:

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

print purify([4, 5, 3, 4])

OUTPUT: [4,3,4] WHY?????

I know about the remove(), I have read about it, for this result, [1,2,3], it prints the correct result, but for some of the inputs, it is like insane.

The generic answer given was to make a new list and append it to the new list based upon the check whether the elem%2 == 0 and return it

But my question is that why ain't my code is working?? What is going wrong in the logic here? Thanks in advance :)

Upvotes: 0

Views: 309

Answers (2)

Sotos
Sotos

Reputation: 51582

Here is a vectorized method to go about it via numpy arrays,

import numpy as np

ar1 = np.array([4, 5, 3, 4])
ar1[ar1 % 2 == 0]
#array([4, 4])
#or coerce to list
list(ar1[ar1 % 2 == 0])
#[4, 4]

Upvotes: 1

Sagar Rana
Sagar Rana

Reputation: 568

Issue is while you loop when you found odd number 5 then you delete that but the loop hasn't finished yet. And you delete from that loop so, next time it iterate it will skip the number 3.

If you simply print it:

def purify(lst):
  for ele in lst:
    print(ele)
    if ele % 2 != 0:
      lst.remove(ele)
  return lst

print purify([4, 5, 3, 4])

Value is:

4
5
4
[4, 3, 4]

So, where is number 3 in iteration?

Upvotes: 1

Related Questions