Purify


#1



If I write if i % 2 == 0, and then append, it works, but if i write it as i % 2 != 0 and try to remove
these items, something goes wrong. What did i do wrong?


 def purify(remove_odds):
    even_list = []
    for i in remove_odds:
        if i % 2 != 0:
            even_list.remove(i)
    return even_list
    
print purify([1,2,3,4,5])


#2

Removing from a list we are iterating shifts everything left, so misses some elements. But that's just the half of it. You are trying to remove elements that do not exist. even_list is empty.

Consider the following:

def purify(n):
    for i in range(len(n)-1, -1, -1):
        if n[i] % 2:
            n.remove(n[i])

In theory, this starts from the right and works to the left, so removing is always to the right of the direction of iteration. Any shifting that takes places does not affect future iterations.


#3

Excellent, lots of learning and practicing still ahead of me. Thank you.


#4

Note the corrections in the above code, after testing.

>>> print (purify([1,2,3,4,5,6,7,8,9]))
[2, 4, 6, 8]
>>>

#5

why is the line

if n[i] % 2:

just as good as

if n[i] % 2 != 0: ?


#6

It relates to how Python interprets conditional expressions.

if ___:

is always a boolean, no matter what the expression is comprised of. The evaluation is done by converting everything in the expression to a boolean based upon its truthiness.

Any value that is not 0, '', "", or, None is treated as truthy and given a boolean True. All of the above are falsy and given a boolean of False.

n[i] % 2

will be truthy if the value is 1, and falsy if 0. So the != 0 part, while valid, is redundant.


#7

I need to crochet that on a pillow. Very useful. Thank you.


#8

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