List comprehension with if statement

160
May 04, 2018, at 12:21 PM

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?

Answer 1

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]
Answer 2

You put the if at the end:

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

List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:

outputlist = []
for y in a:
    if y not in b:
        outputlist.append(y)

Your version tried to do this instead:

outputlist = []
if y not in b:
    for y in a:
        outputlist.append(y)

but a list comprehension must start with at least one outer loop.

Answer 3

This is not a lambda function. It is a list comprehension.

Just change the order:

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

list comprehension formula:

[<value_when_condition_true> if <condition> else <value_when_condition_false> for value in list_name]

thus you can do it like this:

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

Only for demonstration purpose : [y if y not in b else False for y in a ]

Rent Charter Buses Company
READ ALSO
Commands ending with Semicolon

Commands ending with Semicolon

I have two questions that i need helphow to pass following commands after one another using paramiko? eaw BSC1 that connects to a bsc and rxmsp:moty=rxotrx; for TG list

341
python stretched exponential formula in powerlaw package [on hold]

python stretched exponential formula in powerlaw package [on hold]

what is the exact formula of stretched exponential in python powerlaw package?

193
Python: error handling with recursive function in error

Python: error handling with recursive function in error

This is my third questionI've already been voted off of the island twice now on stack overflow, so I'm feeling a little iffy about posting

181