How to use list comprehension with if statement with Python?

Sometimes, we want to use list comprehension with if statement with Python.

In this article, we’ll look at how to use list comprehension with if statement with Python.

How to use list comprehension with if statement with Python?

To use list comprehension with if statement with Python, we put the if expression at the end of the list comprehension expression.

For instance, we write

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

to get the values of y in list a that’s not in list b.

Conclusion

To use list comprehension with if statement with Python, we put the if expression at the end of the list comprehension expression.