Identify the different components of a list comprehension statement.
Implement filtering using list comprehension.
List comprehensions
A list comprehension is a Python statement to compactly create a new list using a pattern.
The general form of a list comprehension statement is shown below.
list_name = [expression for loop_variable in iterable]
list_name refers to the name of a new list, which can be anything, and the for is the for loop keyword. An expression defines what will become part of the new list. loop_variable is an iterator, and iterable is an object that can be iterated, such as a list or string.
Filtering using list comprehensions
List comprehensions can be used to filter items from a given list. A condition is added to the list comprehension.
list_name = [expression for loop_variable in container if condition]
In a filter list comprehension, an element is added into list_name only if the condition is met.
Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.
These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.