Fix Python – List comprehension with if statement

Question

Asked By – OrangeTux

I want to compare 2 iterables and print the items which appear in both iterables.

>>> a = ('q', 'r')
>>> b = ('q')


# Iterate over a. If y not in b, print y.
# I want to see ['r'] printed.
>>> print([ y if y not in b for y in a])
                              ^

But it gives me a invalid syntax error where the ^ has been placed.
What is wrong about this lamba function?

Now we will see solution for issue: List comprehension with if statement


Answer

You got the order wrong. The if should be after the for (unless it is in an if-else ternary operator)

[y for y in a if y not in b]

This would work however:

[y if y not in b else other_value for y in a]

This question is answered By – Volatility

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0