Understand Python Filtered List Comprehensions for Beginners – Python Tutorial

By | August 26, 2019

Python filterd list comprehensions is defined as:

[ function_with_ee_as_parameters for each_element_in_sequence(ee) in sequence if ee_is_true_in_expression ]

In this tutorial, we will discuss how to use python filtered list comprehensions correctly.

Process of filterd list comprehensions execution

1.Run for in

for each_element_in_sequence(ee) in sequence

Iterating each element in sequence.

2.Check each element is true or not in expression

if ee_is_true_in_expression

You can create an expression in if statement for each element in squence.

3.Run function_with_ee_as_parameters

if ee_is_true_in_expression is true, then we will use this ee as a parameter to run function_with_ee_as_parameters.

4.Use the return value of  function_with_ee_as_parameters to create a new list

Here is an example.

list = [1, 2, 3, 4, 5]
def d(x):
    return 2 * x

x = [d(e) for e in list if e % 2 == 0]
print(x)

First, we will iterate each integer in python list.

Second, Check each integer in python list is e % 2 == 0

Third, if e % 2 == 0, we will pass e as a parameter into d(x) function

Third, we will use the return value of d(x) to create a new python list.

The new python list is:

[4, 8]

Leave a Reply