List Methods and Operations
List comprehensions are a concise syntax for creating a new list by transforming or filtering elements from an existing list.
From Source to Result
A list comprehension creates a new list from an existing iterable. It can transform each source item, filter items according to a condition, or do both. The important idea is that the source and the resulting list are separate parts of the operation: each source item is considered, and some value is placed into the new list.
What do you think happens?
Suppose a source list contains 2, 4, and 6, and a comprehension transforms each item by multiplying it by 2. Which values should appear in the new list?
Reveal answer
Answer: [4, 8, 12]
The expression is applied to each source item. Multiplying 2, 4, and 6 by 2 produces 4, 8, and 12.
The Three-Part Pattern
The basic list comprehension pattern is [expression for item in iterable if condition]. The condition is optional. The expression determines what is added to the new list, the item represents the current value taken from the iterable, and the iterable supplies the source values.
In this example, item is the current source value, numbers is the iterable, and item * 2 is the expression. There is no condition, so every item from numbers contributes one transformed value to the new list.
Tracing Each Item
A useful way to read a comprehension is to trace one source item at a time. The iterable supplies an item. If a condition exists, that item is checked. When the condition passes, the expression is evaluated and its result is added to the new list. Without a condition, the expression is evaluated for every item.
Doubling Source Values
Transform the source values 2, 4, and 6 by multiplying each one by 2.
Read the iterable: The source iterable supplies 2, then 4, then 6.
Apply the expression: The expression item * 2 produces 4 from 2, 8 from 4, and 12 from 6.
Build the result: The transformed values are placed in a new list in the order produced.
[4, 8, 12]
Transforming Existing Lists
Use a comprehension for transformation when every source item should produce a corresponding result. The expression can describe the changed value, while the iterable identifies the values to transform. This creates a new list rather than describing a change to the source list.
["ANA", "BO", "CY"]Filtering with Conditions
A condition is optional, but when included it controls which source items contribute to the result. Each source item is checked against the condition. If it passes, the expression is applied and the result is added. If it does not pass, that item contributes nothing to the new list.
[2, 4]Here, the condition is evaluated before the expression contributes a value to the result. The values 1 and 3 do not pass the condition, while 2 and 4 do. Because the expression is simply number, the passing values are added without transformation.
Comprehension or Loop
A list comprehension expresses the same essential movement as a loop: take items from an iterable, optionally check a condition, apply an expression, and add passing results to a new list. The comprehension places these parts into one list-building expression.
The comprehension above is compact because the source, current item, and transformation are expressed together. When reading it, start with the iterable and then trace the current item through the expression. This keeps the execution order clear even though the written order begins with the expression.
Nested Source Iteration
Nested list comprehensions combine multiple sources. The outer loop runs first. For each item selected by the outer loop, the inner loop runs completely. This means the resulting order follows the outer items, with all inner items considered for each outer item.
[(1, "a"), (1, "b"), (2, "a"), (2, "b")]The outer value 1 is considered first, and the inner loop produces both pairs involving 1. Then the outer value 2 is considered, and the inner loop produces both pairs involving 2. Reading nested comprehensions as an outer loop containing a complete inner loop helps prevent ordering mistakes.
Mistakes Beginners Make
Leaving out the expression
The comprehension needs an expression that determines the value added to the new list.
Fix:
[item for item in numbers]Leaving out the iterable
The comprehension must identify the source of the items being processed.
Fix:
[item * 2 for item in numbers]Treating the condition as the result
This expression is valid, but it filters items rather than transforming them. If the intended result is a transformed list, the expression must show that transformation.
Fix:
[item * 2 for item in numbers if item % 2 == 0]Forgetting the brackets
The basic list comprehension syntax uses square brackets to form the new list.
Fix:
[item * 2 for item in numbers]Misreading nested order
In a nested comprehension, the outer loop runs first and the inner loop runs completely for each outer item.
Fix:
Trace every inner value for the first outer item before moving to the next outer item.
Practice the Flow
Write a list comprehension that takes the source values [3, 5, 8, 10], keeps only values that pass the condition value > 5, and transforms each passing value by multiplying it by 2. Before checking your result, trace each source item through the condition and then through the expression.
Hints
- Use the expression value * 2.
- Place the source list after for value in.
- Put the condition after if.
Filtering and Transforming Together
Process [3, 5, 8, 10] by keeping values greater than 5 and doubling the values that remain.
Check each source item: The condition value > 5 rejects 3 and 5, and accepts 8 and 10.
Apply the expression: The expression value * 2 transforms 8 into 16 and 10 into 20.
Build the result: Only the transformed values from passing items are placed in the new list.
[16, 20]
Key Takeaways
- A list comprehension creates a new list by transforming or filtering values from an iterable.
- Its basic pattern is [expression for item in iterable if condition], with the condition optional.
- The iterable supplies items, the condition decides which items continue, and the expression determines what is added.
- Tracing one item at a time makes transformations, filters, and nested comprehensions easier to understand.
- In nested comprehensions, the outer loop runs first and the inner loop completes for each outer item.
Key Takeaways
- List comprehensions provide concise syntax for creating a new list from an iterable.
- The expression transforms the current item, while the optional condition filters items.
- Each source item is checked and, when accepted, contributes the expression result to the new list.
- Nested comprehensions run the outer loop first and complete the inner loop for each outer item.
- Debugging is easier when the expression, iterable, condition, and item flow are examined separately.