Using if for multiple input lists in Python list comprehension
<p>How do you use an if statement in a list comprehension when there are multiple input lists.  Here is the code that I'm using and the error that I'm getting: </p>

<p>(I get that it's not able to apply modulus to a list, but not sure how to specifically reference the x in each of the lists as it iterates through them)</p>

<pre><code>a = [1,2,3]
b = [4,5,6]

nums = [x**2 for x in (a,b) if x%2==0]
print(nums)

TypeError: unsupported operand type(s) for %: 'list' and 'int'
</code></pre>

<p>This isn't a cause with the <code>if</code> statement, the issue here is with <code>x in (a, b)</code>. When that executes, <code>x</code> takes on a <code>list</code> value (first <code>a</code>, then <code>b</code>) and then Python will try try to execute your <code>if</code> condition on it, an expression of the form:</p>

<pre><code>[1, 2, 3] % 2
</code></pre>

<p>is done, which obviously isn't allowed.</p>

<p>Instead, use <a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow"><code>chain</code></a> from <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow"><code>itertools</code></a> to chain both lists together and make <code>x</code> take values from them:</p>

<pre><code>a = [1,2,3]
b = [4,5,6]

nums = [x**2 for x in chain(a,b) if x%2==0]
print(nums)
[4, 16, 36]
</code></pre>

<p>If you're using Python <code>&gt;= 3.5</code> you could also unpack in the list literal <code>[]</code>:</p>

<pre><code>nums = [x**2 for x in [*a, *b] if x%2==0] 
</code></pre>

python python-3.x list-comprehension