List, Set, Dictionary Comprehensions in Python
Let’s learn about the list, dictionary, set comprehensions in python.
Comprehensions in Python:
The comprehension consists of a single expression followed by at least one for
clause and zero or more for
or if
clauses.
There are three comprehensions in Python.
List Comprehensions:
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable or to create a subsequence of those elements that satisfy a certain condition. — python docs
Syntax:
[expression for item in iterable if conditional]
The expression can be any arbitary expression, complex expressions, tuple, nested functions, or another list comprehension.
This is equivalent to
for item in iterable:
if conditional:
expression