Skip to content

Python list comprehension filter | Example code

  • by

Use Conditional statements in list comprehension to filter out data (New list) in python. Generators and list comprehensions are more pythonic than chainable functions.

Python example filtering elements in List Comprehensions

Simple example code list comprehension with a filter or conditional statement.

even_squares = [x * x for x in range(10) if x % 2 == 0]



Python list comprehension filter

Another Example

Extract vowels and consonants along with their indices.

a = "HELLO"
l = list(a)
vow = [(x, i) for i, x in enumerate(l) if x in ['A', 'E', 'I', 'O', 'U']]
cons = [(x, i) for i, x in enumerate(l) if x not in ['A', 'E', 'I', 'O', 'U']]



[(‘E’, 1), (‘O’, 4)]
[(‘H’, 0), (‘L’, 2), (‘L’, 3)]

Why does Python list comprehension filter have a different syntax for if-else?


List comprehension filter without else clause

squares = [x**2 for x in range(20) if x % 2 == 0]

List comprehension filter with else clause

squares = [x**2 if x % 2 == 0 else x + 3 for x in range(20)]

The if-else clause had to be moved to the beginning of the list comprehension after the expression x**2.

The first line is to list comprehension with a filter. It builds a list of squares of x for only those xs for which x % 2 == 0.

The second line is NOT listed comprehension with a filter. It’s just ordinary unfiltered list comprehension using the ternary operator


Do comment if you have any doubts and suggestions on this Python List tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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