Comprehension Syntax in Python
Description
When using a for
loop to create an object, the syntax where the loop itself is written within the object is called a comprehension. It’s a method with good readability, and Python supports list, set, and dictionary comprehensions. Rather than a long explanation, let’s look at the examples below.
Code
List
The most basic way to create a list of squares is as follows.
>>> squares = []
>>> for i in range(1, 7):
... squares.append(i**2)
# [1, 4, 9, 16, 25, 36]
A comprehension involves writing a for
loop within the list, as shown below.
>>> squares = [i**2 for i in range(1, 7)]
# [1, 4, 9, 16, 25, 36]
You can add conditions or use nested loops as well. However, if the loop itself becomes complex in this way, the general loop syntax might be easier to read.
>>> odd_squares = [i**2 for i in range(1, 7) if i % 2 != 0 ]
# [1, 9, 25]
>>> tuples = [(i, j) for i in range(3) for j in range(2)]
# [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
Set and Dictionary
The same approach can be used for sets and dictionaries.
>>> fruits = {len(word) for word in ["apple", "banana", "pear", "orange"]}
# {4, 5, 6}
>>> word2len = {word: len(word) for word in ["apple", "banana", "pear"]}
# {'apple': 5, 'banana': 6, 'pear': 4}