Python Comprehensions
Python comprehensions are a unique way to process data, allowing the construction of a new data sequence from an existing one.
Python supports comprehensions for various data structures:
- List comprehensions
- Dictionary comprehensions
- Set comprehensions
- Tuple comprehensions
List Comprehensions
The format for list comprehensions is:
[expression for variable in list]
[out_exp_res for out_exp in input_list]
or
[expression for variable in list if condition]
[out_exp_res for out_exp in input_list if condition]
- out_exp_res: The expression for the elements of the list, which can be a function that returns a value.
- for out_exp in input_list: Iterates over input_list and passes out_exp to the out_exp_res expression.
- if condition: A conditional statement that filters out unwanted values.
Filter out strings with length less than or equal to 3 from a list and convert the remaining to uppercase:
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 Comprehensions
The basic format for dictionary comprehensions is:
{ key_expr: value_expr for value in collection }
or
{ key_expr: value_expr for value in collection if condition }
Create a dictionary using strings and their lengths:
Example
listdemo = ['Google','tutorialpro', 'Taobao']
# Create key-value pairs where the key is the string and the value is its length
>>> newdict = {key: len(key) for key in listdemo}
>>> newdict
{'Google': 6, 'tutorialpro': 6, 'Taobao': 6}
Create a dictionary with three numbers as keys and their squares as values:
Example
>>> dic = {x: x**2 for x in (2, 4, 6)}
>>> dic
{2: 4, 4: 16, 6: 36}
>>> type(dic)
<class 'dict'>
Set Comprehensions
The basic format for set comprehensions is:
{ expression for item in Sequence }
or
{ 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}
Filter out letters that are not 'a', 'b', or 'c' and print the rest:
Example
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'d', 'r'}
>>> type(a)
<class 'set'>
Tuple Comprehensions (Generator Expressions)
Tuple comprehensions can use ranges, tuples, lists, dictionaries, and sets to quickly generate a tuple that meets specified requirements.
The basic format for tuple comprehensions is:
(expression for item in Sequence)
or
(expression for item in Sequence if conditional)
Tuple comprehensions are used in the same way as list comprehensions, but use parentheses ()
instead of brackets []
, and return a generator object.
For example, we can generate a tuple containing numbers 1 through 9 with the following code:
Example
>>> a = (x for x in range(1, 10))
>>> a
<generator object <genexpr> at 0x7faf6ee20a50> # Returns a generator object
```python
tuple(a) # Using the tuple() function, you can directly convert a generator object into a tuple
(1, 2, 3, 4, 5, 6, 7, 8, 9)