0

While doing some codewars, i stumbled upon the following issue, which i could not understand:

def move_zeros(array):
    for idx, element in enumerate(array):
        if (element == 0) and not (type(element) == bool):
            print(element, idx, type(element))
    
    return array

move_zeros([0,1,None,2,False,1,0])

Outputs

0 0 <class 'int'>
0 6 <class 'int'>

just as expected.

But now, when i try the following, the bool gets converted to an integer, although i am trying to prevent this. Why is it still happening?

def move_zeros(array):
    for idx, element in enumerate(array):
        if (element == 0) and not (type(element) == bool):
            print(element, idx, type(element))
            array.remove(0)
            array.append(0)
    
    return array

move_zeros([0,1,None,2,False,1,0])

Output:

0 0 <class 'int'>
0 5 <class 'int'>
0 6 <class 'int'>
  • 2
    Don't modify a list while you're iterating over it. – Barmar Dec 18 '20 at 16:19
  • `array.remove(0)` doesn't mean "remove *this* zero". It removes the *first* zero, even if that zero is `0.0` or `False`. – user2357112 Dec 18 '20 at 16:22
  • Yes that explains why the result is wrong, however, the print statement is executed before the bool object is handled inside the loop. Why is it converted then? – pmoritz Dec 18 '20 at 16:28

0 Answers0