Python

Python List Comprehension

Python List Comprehension

This tutorial covers Python list comprehension.

List comprehension offers a more efficient and flexible way of managing lists.

It also provides neatness to Python code.

The concept behind list comprehension is similar to the “short-form if statements” or “lambda functions“. The code can be executed in one single line.

Most commonly, this operation creates new lists from a conditional iteration (similar to a “for” loop).

Below is a structural example.

# Example of a list
list = ["item", "item2", "item3"]

# For loop
for item in list:
    print(item)

# List Comprehension
[item for item in list]

Let’s dive into several examples of list comprehensions.

For instance, let’s multiply each item by 2.

someList = ["blue", "red", "white", "yellow"]
multiplyList = [item*2 for item in someList]

print(multiplyList)

# Output ['blueblue', 'redred', 'whitewhite', 'yellowyellow']

Python also allows conditions inside list comprehensions.

The following example prints all items that have the letter “o“.

someList = ["blue", "red", "white", "yellow"]
ifList = [item for item in someList if "o" in item]

print(ifList)

# Output ['yellowyellow']

Let’s look at another approach, for instance, including built-in functions.

Let’s display all items (having the letter “l”) and convert all letters uppercase.

someList = ["blue", "red", "white", "yellow"]
upperList = [item.upper() for item in someList if "l" in item]

print(upperList)

# Output ['BLUE', 'RED', 'WHITE', 'YELLOW']

Lists can work with numbers as well.

Below is an example of creating new list with all integers as absolute values (positive).

someList = [4, -11, 7, -2]
absList = [abs(item) for item in someList]

print(upperList)

# Output: [4, 11, 7, 2]

We can also create expressions.

Below is a scenario of the expression (number + number) * 2. Only if the number in the list is higher than zero.

someList = [4, -11, 7, -2]
expList = [(item + item) ** 2 for item in someList if item > 0]

print(expList)

# Output: [64, 196]

There is an option to move the conditional statement in front as an expression filter (instead as a condition).

The following instance creates the expression (number + number) * 2 for number over 0. For anything else, it prints the message “Negative”.

someList = [4, -11, 7, -2]
expList = [(item + item) ** 2 if item > 0 else "Negative" for item in someList]

print(expList)

# Output: [64, 'Negative', 196, 'Negative']

Next: Python Decorators