Including an AND statement in a Python List Comprehension
<p>I'm trying to create a function for an array. The array will go in and if the value is 0 it will be put to the back of the list. My function works most of the time, but the only issue is that the Boolean value False keeps getting interpreted as 0. I've created an AND statement to differentiate 0 and False, but it is not working, and I can't figure out why. Can you not have AND statements in list comprehension? </p>

<pre><code>def move_zeros(array):
    [array.insert(len(array), array.pop(array.index(x))) for x in array if x == 0 and x is not False]
    return array
</code></pre>

<p>I've added two examples.One works. The other doesn't for what I'd like to accomplish. </p>

<p>Input: [1,"a", 2, 0, 3, "b"] Output: [1, "a", 2, 3, "b", 0] This works</p>

<p>Input: [1, False, 2, 0, 3, "b"] Output: [1, 2, 3, "b", False, 0] This doesn't work, because False is being moved to the end of the list when I want to pass over it.</p>

<p>It is probably a bad idea to try to make a semantic distinctions between <code>0</code> and <code>False</code> when filtering a list, but if you have a good reason to do so there are a couple of ways that might work in your situation.</p>

<p>A somewhat hackish approach which works in CPython is to use <code>is</code> rather than <code>==</code>:</p>

<pre><code>def move_zeros(array):
    zeros = 0
    new_array = []
    for x in array:
        if not x is 0:
            new_array.append(x)
        else:
            zeros += 1
    return new_array + [0]*zeros
</code></pre>

<p>As @chepner points out, this is implementation dependent. A more robust approach which works in Python 3 is to use <code>isinstance()</code>:</p>

<pre><code>def move_zeros(array):
    zeros = 0
    new_array = []
    for x in array:
        if x != 0 or isinstance(x,bool):
            new_array.append(x)
        else:
            zeros += 1
    return new_array + [0]*zeros
</code></pre>

<p>Using either definition:</p>

<pre><code>&gt;&gt;&gt; move_zeros([1, False, 2, 0, 3, "b"])
[1, False, 2, 3, 'b', 0]
</code></pre>

python arrays list-comprehension