Advanced List Comprehension with Conditions
List comprehension creates a new sequence from an existing one by applying a transformation to each item in a single, compact line.
From Source Data to a New List
A common programming task begins with data in one form and ends with a new list in another form. You may need to convert string values into integers, create uppercase versions of names, or keep only items that meet a requirement. List comprehension provides a compact way to build that new list by processing items from an existing sequence.
What do you think happens?
Suppose the source list is [1, 2, 3, 4] and the condition keeps only even values. Which source items can reach the output list?
Reveal answer
Answer: Only 2 and 4
A condition filters the source items. An item that satisfies the condition continues to the expression and can be placed in the new list; an item that does not satisfy it is skipped.
The Item Processing Path
A list comprehension processes the source sequence one item at a time. The current item is represented by a variable. When a filtering condition is present, the item is checked before the transformation is used for the output. Items that pass the condition are transformed by the expression and added to the new list. Items that fail the condition do not contribute an output item.
Conditional Comprehension Syntax
A list comprehension uses square brackets around an expression, a variable representing the current item, and an iterable providing the source data. A conditional list comprehension adds a condition that determines which source items are included.
Read the pattern from left to right as: compute this output value, for each current item in the source data, but include the item only when the condition is satisfied.
Loop and Comprehension Equivalence
The conventional multi-line approach initializes an empty list, loops through the source sequence, transforms each selected item, and appends the result. A comprehension combines those same operations into one list-building expression. Comparing the two forms helps you see that the compact version is not a different goal; it is a shorter representation of the same processing pattern.
| Traditional loop | List comprehension |
|---|---|
| Initialize an empty list | Square brackets create the result list |
| The for loop visits each source item | for variable in iterable visits each source item |
| An if statement selects items | if condition selects items |
| Transform the current item | The expression produces the transformed value |
| append() adds the transformed value | The comprehension adds the expression result |
Tracing a Filtered Transformation
Keep and Convert Selected Values
Create a new list containing integer values converted from strings, but include only values greater than 7.
Start with the iterable: The source data is the list of string values ["4", "7", "10", "13"].
Bind the current item: The variable x represents one string from the source list during each repetition.
Apply the condition: The condition checks whether the converted value is greater than 7. The values 4 and 7 fail, while 10 and 13 pass.
Evaluate the expression: For the values that pass, int(x) produces the integer output value.
Build the result: The converted values from the passing items are placed into the new list.
The resulting list is [10, 13].
[10, 13]Notice the difference between the condition and the expression in this example. The condition decides whether a source item is selected. The expression int(x) determines what value is stored for each selected item. The result is therefore not a copy of the selected strings; it is a new list of converted integers.
True and False Paths
A condition creates two possible paths for each item. When the condition is true, the item continues to the expression and contributes one result value. When the condition is false, the item is skipped and contributes no result value. This is how a comprehension can filter an existing sequence while also transforming the items it keeps.
names = ["Ada", "Lin", "Maya"] uppercase_long_names = [name.upper() for name in names if len(name) > 3] print(uppercase_long_names)
Mistakes Beginners Make
Forgetting the square brackets
The list comprehension is expressed as a list-building operation enclosed in square brackets.
Fix:
[int(x) for x in values]Using the wrong variable name
The expression refers to value, but the loop variable is x.
Fix:
[int(x) for x in values]Putting the for clause before the expression
The expression comes first in the comprehension pattern.
Fix:
[int(x) for x in values]Confusing the condition with the output expression
The expression determines the value produced for the result list. A condition determines which items are included.
Fix:
[x for x in values if x > 7]
Choosing the Clearer Form
List comprehension is well suited to a simple transformation or filtering task. It combines initialization, iteration, transformation, filtering, and adding results into a concise line. A traditional for loop may be clearer when the logic becomes complex or requires multiple steps.
| Prefer a comprehension when | Prefer a traditional loop when |
|---|---|
| The task creates a new list from an existing sequence. | The logic requires multiple steps. |
| The transformation and condition can be understood in one line. | Several operations would make the compact line difficult to read. |
| The shorter form remains readable. | The expanded structure makes the process clearer. |
Practice the Transformation
Rewrite this traditional loop as a list comprehension: words = ["cat", "elephant", "dog", "giraffe"] long_words = [] for word in words: if len(word) > 3: long_words.append(word.upper()) Your comprehension should keep only the longer words and store their uppercase forms.
Hints
- The output expression should produce the uppercase form.
- The loop variable is word and the iterable is words.
- Place the filtering condition after the iterable.
['ELEPHANT', 'GIRAFFE']Key Takeaways
- A list comprehension creates a new sequence from an existing one by processing each source item.
- Its core parts are an expression, a current-item variable, and an iterable.
- A condition filters the source items: passing items reach the expression, while failing items are skipped.
- A comprehension corresponds to a loop that initializes a list, iterates, optionally filters, transforms, and appends.
- Use a comprehension for simple, readable transformations; use a traditional loop when multiple steps make the compact form unclear.
Key Takeaways
- List comprehension builds a new list from existing data.
- The expression produces each output value, the variable represents the current item, and the iterable supplies the source data.
- A condition controls which items are included.
- The compact form is equivalent to a simple loop with append(), but a traditional loop can be clearer for complex logic.