Python List Comprehension

Master Python list comprehensions with our comprehensive guide. Learn how to create concise and efficient lists using list comprehensions with practical examples
E
Edtoks2:32 min read

List comprehensions are a concise way to create lists in Python. They allow you to generate new lists by applying an expression to each item in an existing iterable (e.g., a list, tuple, or range) and optionally filtering the items based on a condition. List comprehensions are a powerful tool for writing clean and readable code.

Here's the basic syntax of a list comprehension:

new_list = [expression for item in iterable if condition]

expression: The expression to be evaluated for each item in the iterable.

item: A variable that represents the current item in the iterable.

iterable: The existing iterable from which elements are taken.

condition (optional): An optional filter that determines whether an item is included in the new list.

Now, let's dive into some examples to illustrate how list comprehensions work:

Example 1: Creating a List of Squares

# Using a for loop
squares = []
for x in range(1, 6):
    squares.append(x**2)

# Using a list comprehension
squares = [x**2 for x in range(1, 6)]

print(squares)  # Output: [1, 4, 9, 16, 25]

In this example, we create a list of squares using both a for loop and a list comprehension. The list comprehension is more concise and readable.

Example 2: Filtering Even Numbers

# Using a for loop
even_numbers = []
for x in range(1, 11):
    if x % 2 == 0:
        even_numbers.append(x)

# Using a list comprehension
even_numbers = [x for x in range(1, 11) if x % 2 == 0]

print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Here, we use a list comprehension to filter even numbers from 1 to 10.

Example 3: Creating a List of Tuples

# Using a for loop
pairs = []
for x in range(1, 4):
    for y in range(1, 4):
        pairs.append((x, y))

# Using a list comprehension
pairs = [(x, y) for x in range(1, 4) for y in range(1, 4)]

print(pairs)
# Output: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

In this example, we create a list of tuples representing pairs of numbers using a nested list comprehension.

Example 4: Using a Condition to Modify Elements

# Using a for loop
original_list = [1, 2, 3, 4, 5]
squared_list = []
for x in original_list:
    if x % 2 == 0:
        squared_list.append(x**2)
    else:
        squared_list.append(x)

# Using a list comprehension with conditional expression
original_list = [1, 2, 3, 4, 5]
squared_list = [x**2 if x % 2 == 0 else x for x in original_list]

print(squared_list)  # Output: [1, 4, 3, 16, 5]

In this example, we use a conditional expression within the list comprehension to square even numbers and keep odd numbers unchanged.

List comprehensions are not only concise but also efficient because they are implemented in CPython, the standard Python interpreter, as a highly optimized feature. They are a valuable tool for creating lists based on existing iterables and applying transformations or filters to the elements.

Let's keep in touch!

Subscribe to keep up with latest updates. We promise not to spam you.