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]
More Related Contents:
- if else in a list comprehension [duplicate]
- Creating a Python list comprehension with an if and break
- how to create a list of lists using list comprehension [closed]
- List comprehension vs map
- List comprehension rebinds names even after scope of comprehension. Is this right?
- Creating a dictionary from a csv file?
- Double Iteration in List Comprehension
- Better to ‘try’ something and catch the exception or test if it’s possible first to avoid an exception?
- Why is a list comprehension so much faster than appending to a list?
- What is a None value?
- if x:, vs if x == True, vs if x is True
- List comprehension vs generator expression’s weird timeit results?
- Putting an if-elif-else statement on one line?
- How can I do assignments in a list comprehension?
- How to check if a string contains an element from a list in Python
- Comprehension for flattening a sequence of sequences? [duplicate]
- How to write inline if statement for print?
- How can I use a conditional expression (expression with if and else) in a list comprehension? [duplicate]
- Weird behavior: Lambda inside list comprehension [duplicate]
- `elif` in list comprehension conditionals
- How to return a subset of a list that matches a condition [duplicate]
- Why list comprehension is much faster than numpy for multiplying arrays?
- How to set local variable in list comprehension?
- remove None value from a list without removing the 0 value
- Comparing numbers give the wrong result in Python
- How to remove duplicate items from a list using list comprehension? [duplicate]
- sum each value in a list of tuples
- Python syntax for “if a or b or c but not all of them”
- Skip elements on a condition based in a list comprehension in python
- Python list comprehension expensive