My new gig has me writing a lot of Python code for the first time, and one sweet, syntactic sugary drink I find myself sipping on quite often is the list comprehension. If you’re a fan of clean, efficient, and readable code like me, then you’ll love this concise way to create and operate on lists. And! It can be more efficient than traditional for-loops. Let’s dive into this elegant feature with a cool example that showcases its power.

The Problem: Filtering and Transforming Lists

Imagine you have a list of numbers, and you want to create a new list that contains the squares of the even numbers from the original list. Traditionally, you might use a for-loop to achieve this:



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

for num in numbers:
    if num % 2 == 0:
        squared_evens.append(num ** 2)

print(squared_evens)

While this works, it’s a bit verbose. Enter list comprehensions.

The Solution: Using List Comprehensions

With list comprehensions, you can achieve the same result in a single line of code:



numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_evens = [num ** 2 for num in numbers if num % 2 == 0]

print(squared_evens)

Let’s break this down:

  • num ** 2 specifies what each element of the new list should be.
  • for num in numbers iterates over each number in the original list.
  • if num % 2 == 0 filters the numbers to include only even ones.

Why List Comprehensions?

  1. Conciseness: As seen in the example, list comprehensions reduce multiple lines of code into a single, readable line.
  2. Performance: They can be faster than using a traditional for-loop because the loop is implemented in C within the Python interpreter.
  3. Readability: Once you get used to the syntax, list comprehensions are often more readable and express the programmer’s intent more clearly.

More Examples

List comprehensions can do more than just filtering and transforming lists. Here are a few more examples:

Creating a List of Tuples

Generate a list of tuples representing the coordinates (x, y) for a grid:



grid_size = 3
coordinates = [(x, y) for x in range(grid_size) for y in range(grid_size)]
print(coordinates)

Flattening a List of Lists

Flatten a list of lists into a single list:



nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened_list = [item for sublist in nested_list for item in sublist]
print(flattened_list)

Happy coding!

Categorized in: