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] print(even_squares)
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']] print(vow) print(cons)
[(‘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
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.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.