Categories
Python Answers

How to use list comprehension with if statement with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *