Error: Unsupported Operand Types
<p>I'm trying to use recursion to return the dot product of two lists, and I'm trying to account for the situation in which I get two lists of different length: I return 0. However, when I try to check for that condition, I get the error: unsupported operand type(s) for &amp;: 'list' and 'list'. Why can't I use the '&amp;' operand for two lists in Python?</p>

<pre><code>def dot(L, K):
    if L+K == []:
        return 0
    elif L == [] &amp; K != []:
        return 0
    elif K == [] &amp; L != []:
        return 0 
    else:
        return L[-1] * K[-1] + dot(L[:-1], K[:-1])
</code></pre>

<p>If you check out python's <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow">Operator Precedence</a> you will see that <code>&amp;</code> has lower precedence than <code>==</code> and <code>and</code></p>

<p>This means you are doing the following:</p>

<pre class="lang-py prettyprint-override"><code>if (L == ([] &amp; K)) != []:
    ...
</code></pre>

<p>As suggested by priya you should be using <code>and</code>.</p>

<pre class="lang-py prettyprint-override"><code>def dot(L, K):
    if L+K == []:
        return 0
    elif L == [] and K != []:
        return 0
    elif K == [] and L != []:
        return 0 
    else:
        return L[-1] * K[-1] + dot(L[:-1], K[:-1])
</code></pre>

<p>However if you wanted to use <code>&amp;</code> (which is the <strong>Binary AND</strong>, and isn't the same thing) you could just use <code>()</code> to force precedence</p>

<pre class="lang-py prettyprint-override"><code>def dot(L, K):
    if L+K == []:
        return 0
    elif (L == []) &amp; (K != []):
        return 0
    elif (K == []) &amp; (L != []):
        return 0 
    else:
        return L[-1] * K[-1] + dot(L[:-1], K[:-1])
</code></pre>

<hr/>

<p>If you're curious why <code>&amp;</code> is likely not what you want read on:</p>

<ul>
<li><code>AND</code> takes two values, converts them to Booleans (<code>True</code> or <code>False</code>) and check that both are <code>True</code></li>
<li><strong>Binary AND</strong> (<code>&amp;</code>) takes two values, converts them to a Number-like value, then performs an operation on their bits</li>
</ul>

<hr/>

<p>Here is how I would implement this function</p>

<pre class="lang-py prettyprint-override"><code>def dot(L, K):
    if len(L) != len(K):
        # Ensure the lists are the same length
        raise ValueError('Can not perform dot product on two differently sized lists')
    elif len(L) + len(K) == 0:
        # See if we've reached the base case
        return 0
    else:
        # Recurse doing dot product
        return L[-1] * K[-1] + dot(L[:-1], K[:-1])


print(dot([6, 2, 6], [5, 1]))
</code></pre>

python math