Python Comprehensions

Python comprehensions are a unique way of data processing that can build a new data sequence structure from one data sequence.

Python comprehensions are a powerful and concise syntax, suitable for generating lists, dictionaries, sets and generators.

When using comprehensions, you need to pay attention to readability and try to keep expressions concise, so as not to affect the readability and maintainability of the code.

Python supports comprehensions for various data structures:

  • List comprehension
  • Dictionary (dict) comprehension
  • Set comprehension
  • Tuple comprehension

List Comprehension

The format of list comprehension is:

[表达式 for 变量 in 列表] 
[out_exp_res for out_exp in input_list]

或者 

[表达式 for 变量 in 列表 if 条件]
[out_exp_res for out_exp in input_list if condition]
  • out_exp_res: the expression for generating elements of the list, which can be a function with a return value.
  • for out_exp in input_list: iterate over input_list and pass out_exp into the out_exp_res expression.
  • if condition: a conditional statement that can filter out values in the list that do not meet the condition.

Filter out string lists with length less than or equal to 3, and convert the remaining to uppercase letters:

Example

>>> names = ['Bob','Tom','alice','Jerry','Wendy','Smith']
>>> new_names = [name.upper()for name in names if len(name)>3]
>>> print(new_names)
['ALICE', 'JERRY', 'WENDY', 'SMITH']

Calculate integers within 30 that are divisible by 3:

Example

>>> multiples = [i for i in range(30) if i % 3 == 0]
>>> print(multiples)
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

Dictionary Comprehension

The basic format of dictionary comprehension:

{ key_expr: value_expr for value in collection }

或

{ key_expr: value_expr for value in collection if condition }

Create a dictionary using strings and their lengths:

Example

listdemo = ['Google','Example', 'Taobao']
# Use the strings in the list as keys and the lengths of the strings as values to form key-value pairs
>>> newdict = {key:len(key) for key in listdemo}
>>> newdict
{'Google': 6, 'Example': 6, 'Taobao': 6}

Provide three numbers, use the three numbers as keys and the squares of the three numbers as values to create a dictionary:

Example

>>> dic = {x: x**2 for x in (2, 4, 6)}
>>> dic
{2: 4, 4: 16, 6: 36}
>>> type(dic)
<class 'dict'>

Set Comprehension

The basic format of set comprehension:

{ expression for item in Sequence }
或
{ expression for item in Sequence if conditional }

Calculate the squares of numbers 1, 2, 3:

Example

>>> setnew = {i**2 for i in (1,2,3)}
>>> setnew
{1, 4, 9}

Determine letters that are not "abc" and output them:

Example

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'d', 'r'}
>>> type(a)
<class 'set'>

Tuple Comprehension (Generator Expression)

Tuple comprehension can use data types such as range intervals, tuples, lists, dictionaries and sets to quickly generate a tuple that meets specified requirements.

The basic format of tuple comprehension:

(expression for item in Sequence )
或
(expression for item in Sequence if conditional )

The usage of tuple comprehension is exactly the same as list comprehension, except that tuple comprehension uses()parentheses to enclose each part, while list comprehension uses square brackets[], additionally, the result returned by tuple comprehension is a generator object.

For example, we can use the following code to generate a tuple containing numbers 1-9:

Example

>>> a = (x for x in range(1,10))
>>> a
<generator object <genexpr> at 0x7faf6ee20a50>  # The returned value is a generator object

>>> tuple(a)       # Using the tuple() function, you can directly convert the generator object into a tuple
(1, 2, 3, 4, 5, 6, 7, 8, 9)
Other Extensions