Skip to main content

What is Python List Comprehension?

basic structure of a list comprehension

Python list comprehension is a concise and expressive way to create lists. It provides a compact syntax for generating new lists by iterating over an existing iterable (like a list, tuple, string, etc.) and applying an expression to each item.

List comprehensions are often used to transform, filter, or combine data elements while creating a new list in a single line of code.

In simple terms, List Comprehension is a shorthand syntax when you want to create a new list from the values of another list.

The basic structure of a list comprehension

new_list = [expression for item in iterable if condition]

Here's a breakdown of the components:

  • expression: This is the operation or transformation that you want to apply to each item in the iterable to generate the elements of the new list.

  • item: This represents the individual elements in the iterable that you are iterating over.

  • iterable: This is the original collection of items you are iterating over (e.g., a list, tuple, string, etc.).

  • condition (optional): You can include an optional condition that filters the items from the iterable. Only items that satisfy the condition will be included in the new list.

Here are a few examples to illustrate how list comprehensions work:

1. Generating a list of squares:

Without using list comprehension:

# without using list comprehension 🙅‍♂️

numbers = [1, 2, 3, 4, 5]

squares = []
for x in numbers:
    squares.append(x**2) #🤮

# Result: squares = [1, 4, 9, 16, 25]

Using list comprehension:

# Using list comprehension 💪

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers] #👌

# Result: squares = [1, 4, 9, 16, 25]

2. Filtering even numbers:

Without using list comprehension:

# without using list comprehension 🙅‍♂️

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
evens = []

for x in numbers:
    if x % 2 == 0:
        evens.append(x) #🤮

# Result: evens = [2, 4, 6, 8]

Using list comprehension:

# Using list comprehension 💪

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
evens = [x for x in numbers if x % 2 == 0] #👌

# Result: evens = [2, 4, 6, 8]

3. Combining two lists:

Without using list comprehension:

# without using list comprehension 🙅‍♂️

fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "red"]
colorful_fruits = []

for fruit, color in zip(fruits, colors):
    colorful_fruits.append(color + " " + fruit) #🤮

# Result: colorful_fruits = ["red apple", "yellow banana", "red cherry"]

Using list comprehension:

# Using list comprehension 💪

fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "red"]
colorful_fruits = [color + " " + fruit for fruit, color in zip(fruits, colors)] #👌

# Result: colorful_fruits = ["red apple", "yellow banana", "red cherry"]

4. Nested list comprehension (creating a matrix):

Without using list comprehension:

# without using list comprehension 🙅‍♂️

matrix = []
for i in range(3):
    row = []
    for j in range(3):
        row.append(i * j)
    matrix.append(row)

# Result: matrix = [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

Using list comprehension:

# Using list comprehension 💪

matrix = [[i*j for j in range(3)] for i in range(3)]

# Result: matrix = [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

Summary

List comprehensions offer a concise way to perform common operations on collections, making your code more readable and often more efficient. However, for very complex expressions or conditions, using a regular loop might be more readable and maintainable.

Just remember the below formula and you've got this in your back pocket!

new_list = [expression for item in iterable if condition]

Post Tags: