0

Any idea why python3 is not treating False as bool? I want to move all the zeros to the end of the list.

def move_zeros(array):

    for i in array:
        if type(i) is not bool:
            if i == 0:
                array.append(int(i)) # catching non bool values that are zeros, adding at the end of the list
                array.remove(i) # removing original
        elif type(i) is bool:
            pass #Here it catches False from the input, it should do nothing but somehow it is moved to the end of the list as zero in the output.

    return array


print(move_zeros(["a", 0, 0, "b", None, "c", "d", 0, 1,
                  False, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9]))

Output:

['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  • 1
    Dont append and remove from your list while looping. – GraphicalDot Apr 19 '20 at 09:03
  • Agreed, that's generally something you should avoid and probably why your False disapears. Python3 does treat false as a bool, you can check this by executing `print(type(False))`. I would rewrite the code. Count the number of zeros in your list and construct a second list with the desired form while looping through the first one. This should get rid of any weird behaviour introduced by modifying the list while looping through it. – Cerenia Apr 19 '20 at 09:08
  • `remove` is almost always the wrong tool even when you're not modifying a list while iterating. Almost always, the operation you want is "remove this element right here", but what `remove` means is "remove the first element that compares equal to this object with `==`". – user2357112 Apr 19 '20 at 09:17

1 Answers1

1

Try this slight modification to your code:

def move_zeros(array):
    new_list = []   # Work a new list
    for i in array:
        print(f"I = {i}")
        if type(i) is not bool:
            if i == 0:
                new_list.append(int(i))
        else:
            pass

    return new_list


print(move_zeros(["a", 0, 0, "b", None, "c", "d", 0, 1,
                  False, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9]))
Frank C.
  • 7,758
  • 4
  • 35
  • 45