Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

9.5 List comprehensions

Learning objectives

By the end of this section you should be able to

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