Categories
Python Answers

How to use if/else in a list comprehension in Python?

Spread the love

Sometimes, we want to use if/else in a list comprehension in Python.

In this article, we’ll look at how to use if/else in a list comprehension in Python.

How to use if/else in a list comprehension in Python?

To use if/else in a list comprehension in Python, we can write it in the following format:

[f(x) if condition else g(x) for x in sequence]

For instance, we write:

x = [1.5, 2.3, 4.4, 5.4, 'n', 1.5, 5.1, 'a']  
x_non_str = [el for el in x if not isinstance(el, str)] 
print(x_non_str)

to use list comprehension and if/else to return an array with non-string elements.

We return anything in x that has not isinstance(el, str) return True.

Therefore, x_non_str is [1.5, 2.3, 4.4, 5.4, 1.5, 5.1].

Conclusion

To use if/else in a list comprehension in Python, we can write it in the following format:

[f(x) if condition else g(x) for x in sequence]

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 *