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]Output:
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']] print[vow] print[cons]Output:
[[E, 1], [O, 4]]
[[H, 0], [L, 2], [L, 3]]
Why does Python list comprehension filter have a different syntax for if-else?
Answer:
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. Its just ordinary unfiltered list comprehension using the ternary operator
Source: stackoverflow.com
Do comment if you have any doubts and suggestions on this Python List tutorial.
Note: IDE:PyCharm2021.3 [Community Edition]
Windows 10
Python 3.10.1
AllPython Examplesare inPython3, 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.
Share this:
Related
- Python lambda if statement | Example code
- Python elif in list comprehension conditionals | Example code
- Python dict comprehension if-else | Example code