Building Lists with Comprehensions

Python often asks you to build a new list from an existing collection: convert measurements, extract name lengths, or retain acceptable records. A list comprehension is an expression that builds a new list by evaluating an output expression for successive source items, optionally keeping only items that meet a condition. It combines list construction and sequence iteration in one readable expression.

Read the expression in execution order

The basic pattern is:


Python
[expression for item in source]


Here, source is an iterable, such as a list. The name item receives each source value in turn. Python evaluates expression using that value and appends the result to the new list. The square brackets identify the result as a list.


Although the output expression appears first in the written syntax, read the comprehension by finding for first: take an item from the source, then calculate its output.


Example: A device records durations in minutes, and you need seconds.


Python
minutes = [2, 5, 1]
seconds = [60 * duration for duration in minutes]


The output calculations are 60 * 2, 60 * 5, and 60 * 1, so seconds becomes [120, 300, 60]. Source order is preserved. If two source items produce equal results, both results remain in the list.


Creating this list does not assign new values to the elements of minutes; it creates a separate list containing the calculated results.

Keep selected source items

A filter is an optional trailing condition that decides whether a source item contributes an element:


Python
[expression for item in source if condition]


For each item, Python checks the condition first. Only items that pass the filter have their output expression evaluated. A failed item contributes nothing; it does not contribute a placeholder.


A source item passes through a filter before its output expression is evaluated and appended, while a failed item is skipped.


Example: Suppose negative durations indicate invalid records.


Python
minutes = [2, -1, 0, 5]
seconds = [60 * duration for duration in minutes if duration >= 0]


The accepted source values are 2, 0, and 5, so the result is [120, 0, 300]. Zero remains because it satisfies duration >= 0.


For one source and one output expression, the governing counting relationship is:


output length=number of source items that pass the filter.\text{output length} = \text{number of source items that pass the filter}.


Without a filter, every source item contributes exactly one result.



Distinguish selection from replacement

A trailing if selects items. A conditional expression before for chooses an output value instead. Its form is value_if_true if condition else value_if_false.


For values = [-3, 0, 4], compare:


Purpose

Comprehension

Result

Keep nonnegative items

[x for x in values if x >= 0]

[0, 4]

Replace negative items with zero

[x if x >= 0 else 0 for x in values]

[0, 0, 4]


Replacement preserves the number of elements because every source item still produces an output. Filtering can shorten the list. You can combine both forms, but trace the trailing filter before choosing the output value.



Use a comprehension when its selection and transformation are easy to identify. Clear variable names make the relationship between each source item and its result easier to check.

What to remember

  • Read for to identify the source and item name, then identify the output expression.
  • A trailing filter decides which source items contribute results.
  • A conditional output expression replaces values without itself removing items.
  • Results preserve source order and retain repeated values.
  • Ordinary transformations build a new list without changing the source list.

Example: Cleaning Device Latency Records

Example: A device records response times in milliseconds. Its list is delays_ms = [250, -1, 600, 0, 1250]. A negative value marks a failed measurement; zero milliseconds is a valid reading. A filter decides whether a source reading contributes an element to the new list.


For conversions, use 1000 milliseconds = 1 second. Give list entries using ordinary Python decimal notation.


a) Write a list comprehension that keeps the valid readings in milliseconds, and state its resulting list.

  1. Accept a reading when ms >= 0. For the failed reading -1, the condition is ________. For the valid reading 0, the condition is ________.
  2. Use the source reading itself as the output expression because this part requires no unit conversion.


Python
valid_ms = [ms for ms in delays_ms if ms >= 0]


The final list is [250, 600, 0, 1250], with every entry measured in milliseconds. The failed reading contributes no placeholder, while the genuine zero remains.


b) Starting from delays_ms, write one comprehension that keeps valid readings and converts them to seconds. State its resulting list.

  1. Keep the same filter, ms >= 0, because validity is determined from the original measurement.
  2. Divide each accepted measurement by 1000. The first conversion is 250 ms ÷ 1000 ms/s = ________, and the next is 600 ms ÷ 1000 ms/s = ________. The remaining accepted conversions are 0.0 s and 1.25 s.


Python
valid_seconds = [ms / 1000 for ms in delays_ms if ms >= 0]


The final list is [0.25, 0.6, 0.0, 1.25], with entries measured in seconds. Python's / operator produces floating-point results here, including 0.0 for the zero reading.


c) A display needs one output per original record. Replace failed measurements with 0.0 seconds instead of removing them, and convert valid measurements to seconds. Write the comprehension and state its output.

  1. Remove the trailing filter so that every source record contributes one result. Select the output using ms / 1000 if ms >= 0 else 0.0.
  2. Process the five source records in order. They produce 0.25 s, the replacement 0.0 s, 0.6 s, the genuine measurement 0.0 s, and 1.25 s.


Python
display_seconds = [ms / 1000 if ms >= 0 else 0.0 for ms in delays_ms]


The final list is [0.25, 0.0, 0.6, 0.0, 1.25], with entries measured in seconds. Both zeros remain: one replaces a failed measurement, while the other comes from a valid source reading. The replacement preserves the original record positions.

A monitoring program stores temperature readings in degrees Celsius and creates an adjusted list using the following Python code. What value does adjusted contain?


Python
temperatures = [-2, 1, 4, 0]
adjusted = [t + 5 for t in temperatures if t > 0]
Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A recording application stores clip durations in minutes and needs a new list containing their durations in seconds. Complete this Python 3 list comprehension by replacing each placeholder with one keyword.


Python
durations = [2, 5, 9]
seconds = [minutes * 60 KEYWORD_1 minutes KEYWORD_2 durations]


Replace KEYWORD_1 with and KEYWORD_2 with .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A registration program must build a list containing the lengths of names with at least five characters. Use len(name) to obtain the current name's length.


Python
names = ["Lina", "Morgan", "Ava", "Priya"]
lengths = [expression for name in names if len(name) >= threshold]


To complete the template, the output expression is , and the integer threshold is .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice