Skip to main content

List Comprehensions

List comprehension is one of the most loved and distinctive features of Python. It provides a concise and elegant way to create lists based on existing lists (or any iterable object).

How does it work?

Basically, it compresses a for loop and an if statement into a single line of code enclosed in square brackets [].

Basic syntax: [expression for element in iterable if condition]

Classic Example: Squaring

Suppose we have a list of numbers and we want to create a new list with the squares of those numbers.

The traditional approach (using a for loop):

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

for n in numbers:
squares.append(n ** 2)

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

With List Comprehension:

numbers = [1, 2, 3, 4, 5]
squares = [n ** 2 for n in numbers]

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

Adding Conditionals (Filters)

You can add an if condition at the end to filter the elements.

Example: Get only even numbers:

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

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

Advantages

  1. Concise: They reduce 3 or 4 lines of code to a single one.
  2. Readable: Once you get used to the syntax, they read almost like natural mathematical language.
  3. Performance: Generally, list comprehensions are slightly faster than using traditional for loops with .append() because they are optimized in Python's underlying C.

⚠️ Clean Code Warning: Use them only when the logic is simple. If your expression includes multiple loops or complex conditions, it is better to use a traditional for loop for the sake of readability.