0
0
Pythonprogramming~3 mins

List comprehension vs loop in Python - When to Use Which

Choose your learning style9 modes available
The Big Idea

What if you could replace many lines of boring loops with just one simple line that does the same job perfectly?

The Scenario

Imagine you have a long list of numbers and you want to create a new list with each number doubled. Doing this by hand means writing a loop that goes through each number one by one and adds the doubled value to a new list.

The Problem

Writing loops for simple list transformations can be slow and repetitive. It's easy to make mistakes like forgetting to add the new item to the list or messing up the loop conditions. This makes your code longer and harder to read.

The Solution

List comprehension lets you do the same task in one clear, short line. It automatically loops through the list and builds the new list for you, making your code cleaner and easier to understand.

Before vs After
Before
doubled_numbers = []
for number in numbers:
    doubled_numbers.append(number * 2)
After
doubled_numbers = [number * 2 for number in numbers]
What It Enables

With list comprehension, you can quickly and clearly transform lists, making your code simpler and faster to write.

Real Life Example

Suppose you have a list of prices and want to apply a 10% discount to each. Using list comprehension, you can do this in one line instead of writing a loop.

Key Takeaways

Loops are manual and can be long and error-prone.

List comprehension makes list transformations concise and readable.

It helps write cleaner and faster code for common tasks.