Skip to content

List compression

List compression is a concise and elegant way to create lists from other sequences (lists, tuples, ranges, etc.) by applying transformations or filters in a single line of code.


  • Lets you write more readable and clean code.
  • Is more efficient than using traditional loops to create lists.
  • Facilitate applying conditions and transformations to elements.

The general syntax is:

[new_expression for element in sequence if condition]
  • new_expression: what you want to add to the new list.
  • element: each value from the original sequence.
  • sequence: the collection of data to iterate over.
  • condition (optional): filters the elements that meet the condition.

Suppose you want to obtain a list with the squares of numbers from 1 to 5:

Squares_from_1_to_5.py
squares = [x**2 for x in range(1, 6)]
print(squares)

Output:

[1, 4, 9, 16, 25]

Now, we only want the squares of even numbers:

Squares_of_even_numbers.py
squares_even = [x**2 for x in range(1, 6) if x % 2 == 0]
print(squares_even)

Output:

[4, 16]

The following code does the same, but using a for loop:

Traditional_loop.py
squares = []
for x in range(1, 6):
squares.append(x**2)

As you can see, list comprehension is more compact and easier to read.


  • List comprehension allows you to create new lists concisely and efficiently.
  • You can transform and filter elements in a single line.
  • It is a powerful tool for working with collections in Python.

Are you ready to practice? Try creating a list with the odd numbers from 1 to 20 using list comprehension. .