Purify


#1

Hey guys, for purify 15.12, my code is:

def purify(range):
    for i in range:
        if i%2!=0:
            range.pop(range.index(i))
    return range

but when range=[4,5,5,4], it returns [4,5,4], don't understand why it isn't getting rid of the second 5.

Cheers.


#2

Uhm, there is no second 5. Must be a mistype.

Not sure I would go with the variable name chosen, but that is minor. The mutation of the iterable is the issue. Once you copy a range to a loop, messing with the iterable can mess things up considerably.


#3

Cheers for getting back to me @mtf

Can you elaborate on what you mean?

Thanks!


#4

First off, I would not use the variable name 'range' since that is a keyword, but Python can tell the difference, hence, minor. Still, best practices have to start somewhere.

At the start of the loop the list is mapped for sequential iteration. It's elements compose of the range. Take something off the list and iteration is upset since elements in the list shift to the left to fill the empty space. This will cause some values to be skipped.


#5

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