Course contentsShow
← Python
Lesson 270 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Transforming Data with Basic List Comprehensions

You will be able to replace standard for-loops with concise list comprehension syntax to create new lists from existing iterables.

Transforming Data with Basic List Comprehensions

In this lesson, you will learn how to replace verbose for-loops with concise, readable list comprehension syntax to transform data efficiently.

The Problem with Loops

Up until now, whenever you needed to transform a list—such as squaring every number or converting strings to uppercase—you likely used a standard for-loop. You would initialize an empty list, iterate through your data, apply a transformation, and append the result to the new list:

numbers = [1, 2, 3, 4]
squared = []
for n in numbers:
    squared.append(n * n)

While this works perfectly, it is quite "noisy" for such a simple task. It requires three lines of code just to set up the container and build the results.

The Power of List Comprehensions

Python offers list comprehensions as a more compact, expressive way to create new lists. A list comprehension consists of brackets containing an expression followed by a for clause. It performs the same logical steps as the loop above but packages them into a single, declarative statement.

Here is how you would rewrite the code above:

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

How to Read It

You can think of the syntax [expression for item in iterable] as a sentence: "Give me a list of n * n for every n that is inside numbers."

This approach is not just about saving keystrokes; it is about intent. When you use a list comprehension, you are telling the reader that your primary goal is to transform an existing collection into a new one. Python handles the internal creation and appending process behind the scenes, which is generally faster and less error-prone than manual management.

As you move forward, keep in mind that list comprehensions are designed for readability. If your transformation logic becomes overly complex or requires multiple nested loops, it is often better to stick with a standard for-loop to keep your code maintainable.

Key Takeaway: List comprehensions allow you to condense transformation logic into a single line, making your code more expressive and cleaner than traditional manual loops.