List Comprehensions
Learn about list comprehensions in Python.
We'll cover the following
Definition
A list comprehension is a way of computing a list from a sequence or an iterator. The sequence may be a list, a tuple, a set, the keys of a dictionary, or a string.
General structure
List comprehension statements are always enclosed inside square brackets, []
. The general structure that these statements follow fall in two categories:
- [expression for variable in sequence] returns a list of the expression values when each variable in the sequence is used in the expression.
A list comprehension may include an optional if
test.
- [expression for variable in sequence if condition] returns a list of the expression values for each variable in the sequence that satisfies the condition used in the expression.
List comprehension uses
List comprehensions are powerful and worth getting to know. Here are some simple use cases:
- List comprehensions can be used to apply an expression to every element of a list. You can see this in the following example:
Get hands-on with 1400+ tech skills courses.