List Comprehension
Learn about the usage of list comprehensions in Python.
What are comprehensions?
Comprehensions offer an easy and compact way of creating lists, sets, and dictionaries.
A comprehension works by looping or iterating over items and assigning them to a container like a list, set, or dictionary.
This container cannot be a tuple because a tuple is unable to receive assignments due to its immutability.
List comprehension
List comprehension consists of square brackets containing an expression, followed by a for
clause, and zero or more for
or if
clauses.
The general form of a list comprehension is:
lst = [expression for var in sequence [optional for and/or if]]
Simple examples
Examples of list comprehension are shown below:
Get hands-on with 1200+ tech skills courses.