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?
You got the order wrong. The
if
should be after thefor
(unless it is in anif-else
ternary operator)This would work however:
list comprehension formula:
thus you can do it like this:
Only for demonstration purpose : [y if y not in b else False for y in a ]
You put the
if
at the end:List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:
Your version tried to do this instead:
but a list comprehension must start with at least one outer loop.
This is not a lambda function. It is a list comprehension.
Just change the order: