Working with Lists and List Methods
List comprehension condenses a for loop, empty list initialization, and append pattern into a single, readable line.
From Repeated Steps to One Line
Building a new list from an existing list is a common Python task. The longer form initializes an empty list, loops through source data, transforms each item, and appends each result. A list comprehension expresses that same pattern in a single line. The important idea is not merely that the comprehension is shorter: both forms follow the same logical sequence.
What do you think happens?
What list will be produced when the strings 42, 65, and 12 are converted to integers one at a time?
Reveal answer
Answer: [42, 65, 12]
Each source string is converted separately with int(x), and each converted integer is added to the new list.
The Comprehension Pattern
A list comprehension condenses an empty-list initialization, a for loop, and an append operation into a single readable line. Its basic structure is [expression for variable in iterable]. The expression describes what should be placed in the new list, while the loop variable and iterable describe where the input elements come from.
The square brackets signal that a new list is being created. The expression appears first because it defines the value collected for each item. The for clause then identifies the variable that receives the current item and the iterable that supplies the items.
Mapping the Two Forms
numbers_as_strings = ["42", "65", "12"] integers = [] for x in numbers_as_strings: integers.append(int(x)) total = sum(integers)
119The two versions are structurally equivalent. The traditional loop makes initialization and append explicit. The comprehension removes those separate statements and places the transformation expression before the for clause. Each source string still passes through int(x), and each converted result still enters the new list one element at a time.
Filtering with Conditions
A condition can be added after the iterable to filter the results. The pattern becomes [expression for variable in iterable if condition]. The expression still determines the value placed in the result list, while the condition determines which items are included.
[65, 88]In this example, each string is converted to an integer for the condition. Values greater than 50 pass the condition and are converted into result-list elements. The values 65 and 88 are included, while 42 and 12 are excluded.
Expanding a Comprehension for Debugging
When a comprehension does not produce the expected result, expand it into the longer for-loop pattern. This exposes the source list, the current item, the expression, and the condition as separate parts. You can then inspect whether the iterable is correct, whether the expression transforms the item as intended, and whether the condition includes the right values.
Looking only at the expression and overlooking the iterable.
The expression describes the output value, but the for clause determines which source items are processed.
Fix:
Check both the transformation expression and the source named after in.Treating the condition as the output value.
The condition filters items; it does not replace the expression that supplies result-list elements.
Fix:
Read the expression before for as the collected value and the if clause as the inclusion test.Using a comprehension for logic that has become difficult to read.
The source recommends a traditional for loop when the logic involves multiple steps or complex conditional branches.
Fix:
Expand the operation into a traditional for loop when the comprehension is no longer immediately clear.
Choosing Clearer Syntax
| Prefer a list comprehension | Prefer a traditional for loop |
|---|---|
| A simple, single transformation is applied to each item. | The loop body contains multiple steps. |
| The result fits comfortably on one or two lines. | The logic includes complex conditional branches. |
| The expression is immediately clear to the reader. | Different transformations are performed based on an item's value. |
| A new list is being collected. | Debug information needs to be printed during iteration. |
The decision is therefore about structure, not line count alone. The comprehension and the traditional loop can perform the same basic transformation, but the traditional loop gives complex operations more room to show each step.
Practice and Recall
Rewrite a traditional loop that converts every item in a list of number strings into an integer as a list comprehension. Then add a condition so that only converted integers greater than 50 appear in the result.
Hints
- Place the conversion expression before the for clause.
- Use the source list after in.
- Place the filtering condition after the iterable.
- A list comprehension creates a new list by combining an expression, a loop variable, and an iterable. It follows the same logical pattern as initializing an empty list, iterating through source data, transforming each item, and appending the result. Adding an if condition filters which items enter the result. Expand a comprehension into a traditional for loop when debugging or when the operation becomes difficult to read.
Key Takeaways
- The pattern [expression for variable in iterable] maps directly to a transformation loop.
- Data moves from the source iterable through the expression into a new result list one item at a time.
- An if condition filters which source items are included.
- Expanding a comprehension into a for loop helps isolate an incorrect expression, iterable, or condition.
- Use comprehensions for simple readable transformations and traditional loops for more complex logic.