Skip to main content

Master Python List Comprehension with 10+ Examples

basic structure of a list comprehension
633vw

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]

Frequently Asked Questions

What is Python list comprehension?

List comprehension is a concise syntax for creating lists by iterating over an iterable and applying an expression to each item. The format is: new_list = [expression for item in iterable if condition].

When should I use list comprehension vs a for loop?

Use list comprehension for simple transformations and filtering where the logic fits on one line. Use traditional for loops for complex logic, multiple operations, or when readability suffers.

Can list comprehension have multiple conditions?

Yes, you can chain multiple if conditions: [x for x in items if condition1 if condition2]. You can also use logical operators: [x for x in items if condition1 and condition2].

What is nested list comprehension?

Nested list comprehension creates lists of lists, like matrices. Example: [[i*j for j in range(3)] for i in range(3)] creates a 3x3 multiplication table.

Is list comprehension faster than for loops?

Generally yes, list comprehension is slightly faster because it's optimized at the C level in Python. However, the performance difference is usually negligible for small datasets.


Post Tags: