Python Comprehensions Example

Python language has a unique comprehension syntax, which is equivalent to the existence of syntactic sugar. It can help you to write relatively simple and cool code in some occasions. But without it, it would not have much impact. There are several types of comprehensions in python, we will list them as below one by one.

1. List Comprehensions.

1.1 General List Comprehension.

List comprehension is a fast way to generate lists. It takes the form of a statement enclosed in square brackets, as shown in the following example.

>>> list = [x + x for x in range(1, 6)]

>>> print(list)

[2, 4, 6, 8, 10]

In above list comprehension, first execute the for loop. For each x, put it into x + x for operation. Add the operation results to a new list one by one, until the loop ends to get the final list. It is equivalent to the following code.

>>> list = []
>>> 
>>> for i in range(1, 6):
...     
...     list.append(i + i)
... 
>>> print(list)
[2, 4, 6, 8, 10]

List comprehension gives us a way to generate lists with more complex logic in one line. The core syntax is to encapsulate the generation logic within brackets [].

1.2 List Comprehension With If Condition.

We can add if condition in the list comprehension. In below python source code, we filter x by adding an if clause after it, so only the x value which can be divided by 3 is used in the comprehension.

>>> list = [x + x for x in range(1, 6) if x % 3 == 0]

>>> print(list)
[6]

1.3 List Comprehension With Multiple Variable Loop.

Below list comprehension will loop variable x and y at the same time.

>>> list = [x + y for x in (1,2,3) for y in range(7,10)]

>> print(list)

[8, 9, 10, 9, 10, 11, 10, 11, 12]

1.4 Create List Comprehension From Dictionary.

>>> dict = {"k1":"v1","k2":"v2"}
>>> 
>>> list = [k+"="+v for k,v in dict.items()]
>>> 
>>> print(list)
['k1=v1', 'k2=v2']

2. Dictionary Comprehension.

The list comprehension can be written with brackets [], and the dictionary comprehension can be made with braces {}. Note the writing method of x: x + x means that the key is on the colon left side and the value is on the colon’s right side.

>>> dict = {x: x + x for x in range(1,6)}
>>> 
>>> print(dict)
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
>>> 
>>> type(dict)
<class 'dict'>

3. Set Comprehension.

In addition to dictionary comprehension, braces can also be used as set comprehension.

>>> set = {x for x in 'abracadabra' if x not in 'ar'}
>>> 
>>> set
{'c', 'b', 'd'}
>>> 
>>> type(set)
<class 'set'>

4. Tuple Comprehension.

Sorry, there is no tuple comprehension. For example, if you use round brackets to create tuple comprehension, it will generate an error. Because round brackets are used as the syntax of generators in Python.

>>> tuple = (x for x in range(10))
>>> 
>>> tuple
<generator object <genexpr> at 0x10f9cde50>

To generate tuples in a similar way, you need to explicitly call tuple() function which is tuple’s type conversion function, as follows.

>>> tuple = tuple(x for x in range(9))
>>> 
>>> tuple
(0, 1, 2, 3, 4, 5, 6, 7, 8)