Concepts / Advanced List Comprehension with Conditions

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.

  • Programming
Interactive lab

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

  1. Take the next x from xs (with two for clauses: every y for each x).
  2. Evaluate the if test; when it is False nothing is produced for this item.
  3. Otherwise evaluate the expression and append it (a dict comprehension sets result[key] = value; a repeated key overwrites but keeps its place).
  4. 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.

Educational simulation

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?

  • All four items

  • Only 1 and 3

  • Only 2 and 4

  • No items

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.

source itemone itemxcurrent itemconditionpasses or failsexpressiontransformed valuenew listoutput itembindchecktrueadd
How does each item move from the original iterable through the condition and expression to become an item in the new list?

Conditional Comprehension Syntax

Definition

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.

python
expressionoutput valueforiterationvariablecurrent iteminsource linkiterablesource dataiffilterconditioninclude test
Which part produces the output, which part receives each source item, which part supplies the source data, and where does filtering occur?
Key point

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 loopList comprehension
Initialize an empty listSquare brackets create the result list
The for loop visits each source itemfor variable in iterable visits each source item
An if statement selects itemsif condition selects items
Transform the current itemThe expression produces the transformed value
append() adds the transformed valueThe comprehension adds the expression result

Correspondence between the multi-line loop and the compact comprehension

Before
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.

After
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.

empty listinitializesquare bracketsresult listfor loopiteratefor x in valuesiterateif conditionfilterif conditionfilterint(x)transformint(x)output valueappend()add resultbecomesbecomesbecomesbecomesbuilt into
How do the loop, condition, transformation, and append() operation correspond to parts of the compact comprehension?

Tracing a Filtered Transformation

Worked example

Keep and Convert Selected Values

Create a new list containing integer values converted from strings, but include only values greater than 7.

  1. 1
    Start with the iterable

    The source data is the list of string values ["4", "7", "10", "13"].

  2. 2
    Bind the current item

    The variable x represents one string from the source list during each repetition.

  3. 3
    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.

  4. 4
    Evaluate the expression

    For the values that pass, int(x) produces the integer output value.

  5. 5
    Build the result

    The converted values from the passing items are placed into the new list.

Result

The resulting list is [10, 13].

python
Output
[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.

current itemfrom iterableconditionpass or failexpressionmake outputoutput itemincludedno outputskippedchecktrueaddfalse
What happens to an item when the condition is true versus when the condition is false?
Code walkthrough
names = ["Ada", "Lin", "Maya"]
uppercase_long_names = [name.upper() for name in names if len(name) > 3]
print(uppercase_long_names)
  1. 1
    Ada is checked. Its length does not pass the condition, so it contributes no output.
  2. 2
    Lin is checked. Its length does not pass the condition, so it contributes no output.
  3. 3
    Maya passes the condition, and name.upper() produces MAYA.
  4. 4
    The 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.
Output
['MAYA']

Mistakes Beginners Make

  • Common mistake

    Forgetting the square brackets

    What it looks like
    int(x) for x in values
    Why it fails

    The 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 fails

    The 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 fails

    The 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 fails

    The 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 whenPrefer 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

MEDIUM

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.
python
Output
['ELEPHANT', 'GIRAFFE']

Key Takeaways

  1. 1
    A list comprehension creates a new sequence from an existing one by processing each source item.
  2. 2
    Its core parts are an expression, a current-item variable, and an iterable.
  3. 3
    A condition filters the source items: passing items reach the expression, while failing items are skipped.
  4. 4
    A comprehension corresponds to a loop that initializes a list, iterates, optionally filters, transforms, and appends.
  5. 5
    Use 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.

Related concepts

More concepts starting with A