Advanced List Comprehension with Conditions
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.
Try it: Comprehensions, map() and filter()
That [expr for x in xs if cond] is a loop: for each item Python tests the condition and only then evaluates the expression and appends it — the same result as map() and filter(), a dict comprehension, or a nested pair of for clauses.
How it works
- Take the next x from xs (with two for clauses: every y for each x).
- Evaluate the if test; when it is False nothing is produced for this item.
- Otherwise evaluate the expression and append it (a dict comprehension sets result[key] = value; a repeated key overwrites but keeps its place).
- map(f, xs) applies f to every item; filter(f, xs) keeps the items where f(x) is truthy.
Default run (12 steps): result = [x * 10 for x in xs if x > 4] — Python runs this as a loop over 6 items. … The loop is finished: result = [80, 50, 120, 70] (4 items).
Simplified: Expressions and tests come from a fixed menu of templates with editable numbers over up to 10 ints (and 6 for the second list); no learner code is evaluated.
Loading the simulation…
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
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 |
Correspondence between the multi-line loop and the compact comprehension
values = ["4", "7", "10", "13"]
list_of_ints = []
for x in values:
number = int(x)
if number > 7:
list_of_ints.append(number)The loop explicitly initializes, iterates, filters, transforms, and appends.
values = ["4", "7", "10", "13"]
list_of_ints = [int(x) for x in values if int(x) > 7]The comprehension expresses the transformation and filtering in one list-building line.
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.
- 1Start with the iterable
The source data is the list of string values ["4", "7", "10", "13"].
- 2Bind the current item
The variable x represents one string from the source list during each repetition.
- 3Apply the condition
The condition checks whether the converted value is greater than 7. The values 4 and 7 fail, while 10 and 13 pass.
- 4Evaluate the expression
For the values that pass,
int(x)produces the integer output value. - 5Build 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)- 1Ada is checked. Its length does not pass the condition, so it contributes no output.
- 2Lin is checked. Its length does not pass the condition, so it contributes no output.
- 3Maya passes the condition, and
name.upper()produces MAYA. - 4The new list contains only the transformed value from the passing item.
- The iterable is names.
- The variable name represents the current name.
- The condition keeps names whose length is greater than 3.
- The expression converts each kept name to uppercase.
['MAYA']Mistakes Beginners Make
Common mistake Forgetting the square brackets
What it looks likeint(x) for x in valuesWhy it failsThe list comprehension is expressed as a list-building operation enclosed in square brackets.
Do this instead[int(x) for x in values]Common mistake Using the wrong variable name
What it looks like[int(value) for x in values]Why it failsThe expression refers to value, but the loop variable is x.
Do this instead[int(x) for x in values]Common mistake Putting the for clause before the expression
What it looks like[for x in values int(x)]Why it failsThe expression comes first in the comprehension pattern.
Do this instead[int(x) for x in values]Common mistake Confusing the condition with the output expression
What it looks like[x > 7 for x in values]Why it failsThe expression determines the value produced for the result list. A condition determines which items are included.
Do this instead[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. |
Use the form that keeps the data-processing logic understandable
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
- 1A list comprehension creates a new sequence from an existing one by processing each source item.
- 2Its core parts are an expression, a current-item variable, and an iterable.
- 3A condition filters the source items: passing items reach the expression, while failing items are skipped.
- 4A comprehension corresponds to a loop that initializes a list, iterates, optionally filters, transforms, and appends.
- 5Use a comprehension for simple, readable transformations; use a traditional loop when multiple steps make the compact form unclear.
At a glance
- 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.