Understand Python List Comprehension for Beginners – Python Tutorial

By | August 24, 2019

Python list comprehension can allow us to create a new list by elements in a list. In this tutorial, we will write some examples to help you understand and use it correctly.

A common used python list comprehension is defined as:

[function_with_ee_as_parameter for each_element_in_sequence(ee) in sequence ]

where

sequence: it can be a string, list, tuple or dictionary.

each_element_in_sequence(ee): every element in sequence.

For example:

list = [1, 2, 3, 4, 5]
for ee in list

ee may be 1, 2, 3, 4, 5.

function_with_ee_as_parameter: it can be a function or a simple expression.  Python will use the return value of function or result value of expression to create a new list.

For example:

list = [1, 2, 3, 4, 5]
y = [2 * ee for ee in list]
print(y)

Here,

function_with_ee_as_parameter is a simple expression, python will use 2 * ee to create a new python list.

The example below is equivalent to above.

def d(x):
    return 2 * x

x = [d(e) for e in list]

Here,

function_with_ee_as_parameter is a function, this function will use each element in python list as a parameter to get a return value, then python will use these return value to create a new python list.

The new python list is:

[2, 4, 6, 8, 10]

 

Leave a Reply