Search⌘ K
AI Features

List Comprehensions

Explore how to replace traditional loop-based list creation with Python list comprehensions. Learn to write concise, readable code that transforms sequences into new lists using a single expression, enhancing both clarity and efficiency in your Python projects.

As discussed previously, the for loop is a fundamental construct for iterating over a collection of data. However, when we want to generate a new list from an existing one, the conventional loop-based approach sounds repetitive. This pattern involves initializing an empty list, iterating over each element, and then appending a modified version of that element to the newly created list.

Python provides a more concise alternative known as list comprehensions. A list comprehension reduces this multi-step pattern into a single, readable expression. By doing so, it emphasizes the intended data transformation, resulting in code that is both clearer and more maintainable.

The traditional approach

Suppose we have a list of numbers and we want to create a new list containing their squares. When using a standard for loop, we must manually manage the list construction.

Python 3.14.0
numbers = [1, 2, 3, 4, 5]
# 1. Initialize an empty list
squares = []
# 2. Loop through the sequence
for number in numbers:
# 3. Append the transformed value
squares.append(number ** 2)
print(squares)
  • Line 4: We create an empty list squares to hold our results. ...