Python List Comprehension

The list comprehension is a concise way to create lists in Python. It provides a more readable and expressive syntax for creating a list based on existing lists or iterables.

They are generally more compact and faster than traditional loops and manual list building.

Syntax

new_list = [expression for item in iterable if condition]

Arguments

Parameters Description
expression (output) This is the current item in the iteration, but it also can be the outcome of an operation on the current item.
item This is the object or value in the list or iterable.
iterable (collection) An object that can return one of its elements at a time, such as a list, tuple, set, etc.
condition (Optional) It’s a way to filter out items that don’t meet specific criteria.

Visual representation

Visual representation of explaining list comprehension in Python

Example 1: Creating a simple list of numbers

Creating a simple list of numbers

# This will create a list of numbers from 0 to 6.
numbers = [x for x in range(7)]

# Print the numbers
print(numbers)

Output

[0, 1, 2, 3, 4, 5, 6]

Example 2: Applying a function to each item

Applying a function to each item

# This will create a list of squares of numbers from 0 to 6.
squares = [x**2 for x in range(7)]

# Print the squares
print(squares)

Output

[0, 1, 4, 9, 16, 25, 36]

Example 3: Using if condition

Use list comprehension with conditional if statement

# This will create a list of even numbers between 0 and 6.
even_list = [x for x in range(7) if x % 2 == 0]

# Print the list
print(even_list)

Output

[0, 2, 4, 6]

Example 4: Using if-else

With if-else condition

The if-else allows for more complex decision-making processes within the comprehension.

Here, both the if and else parts come before the for part of the comprehension, which is different from using only if conditions.

result = [x**2 if x % 2 == 0 else x**3 for x in range(7)]

print(result)

Output

[0, 1, 4, 27, 16, 125, 36]

Example 5: Using nested if

Using nested if with list comprehension

Nested if conditions can be used in list comprehensions to apply multiple filters or criteria.

When you have more than one if condition, they can be chained within the comprehension, allowing for more complex filtering.

result = [x for x in range(1, 21) if x % 2 == 0 if x % 3 == 0]

print(result)

Output

[6, 12, 18]

Nested if conditions in list comprehensions can make your code compact, but they can also reduce readability if overused or used in complex scenarios.

Example 6: Nested list comprehension

# Creating a nested list
nested_list = [[1, 2, 3], [4, 5, 6]]

# This flattens a nested_list (list of lists) into a single list.
flattened_list = [num for row in nested_list for num in row]

# Flatten the list
print(flattened_list)

Output

[1, 2, 3, 4, 5, 6]

Example 7: List Comprehension vs For Loop

The main difference between list comprehension and for loop is that list comprehension is more concise and direct, whereas for loop is more verbose but can be easier to read and modify for complex logic.

List comprehension can be more efficient than using a for loop to create lists. They are optimized internally to be faster and more memory-efficient. This is particularly noticeable when working with large datasets.

Here is a code example of list comprehension:

squares = [x**2 for x in range(7) if x % 2 == 0]

print(squares)

Output

[0, 4, 16, 36]

Here is a code example of a for loop:

squares = []

for x in range(7):
  if x % 2 == 0:
    squares.append(x**2)

print(squares)

Output

[0, 4, 16, 36]

Example 8: Transpose of a Matrix

matrix = [[19, 21], [18, 46], [10, 20]]

transpose_mat = [[row[i] for row in matrix] for i in range(2)]

print(transpose_mat)

Output

[[19, 18, 10], [21, 46, 20]]

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.