Python Comprehensions: A Unique Data Processing Method
Python comprehensions offer a powerful and concise way to generate new sequences from existing ones. These comprehensions support creating lists, dictionaries, sets, and even generators.
When using comprehensions, it's essential to focus on readability and keep expressions simple to maintain code clarity and maintainability.
Python supports comprehensions for various data structures:
List Comprehensions
Dictionary Comprehensions
Set Comprehensions
Tuple (Generator) Comprehensions
List Comprehensions
The syntax for list comprehensions is as follows:
[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 used to generate elements for the list, which can be a function that returns values.for out_exp in input_list
: Iterates overinput_list
, passingout_exp
to theout_exp_res
expression.if condition
: A conditional statement that filters values not meeting the specified condition.
Example 1: Filtering and Uppercasing Strings Longer Than 3 Characters
>>> 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']
Example 2: Finding Multiples of 3 Below 30
>>> 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 syntax for dictionary comprehensions is:
{key_expr: value_expr for value in collection}
Or:
{key_expr: value_expr for value in collection if condition}
Example 1: Creating a Dictionary with Strings as Keys and Their Lengths as Values
listdemo = ['Google', 'Runoob', 'Taobao'] >>> newdict = {key: len(key) for key in listdemo} >>> newdict {'Google': 6, 'Runoob': 6, 'Taobao': 6}
Example 2: Creating a Dictionary with Numbers as Keys and Their Squares as Values
>>> 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 syntax for set comprehensions is:
{expression for item in Sequence}
Or:
{expression for item in Sequence if conditional}
Example 1: Calculating Squares of Numbers 1, 2, and 3
>>> setnew = {i**2 for i in (1, 2, 3)} >>> setnew {1, 4, 9}
Example 2: Filtering Out Letters That Are Not 'a', 'b', or 'c'
>>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a {'r', 'd'} >>> type(a) <class 'set'>
Tuple (Generator) Comprehensions
Tuple comprehensions can quickly generate a sequence that meets specified requirements by using data types such as range
, tuples, lists, dictionaries, and sets.
The basic syntax for tuple comprehensions is:
(expression for item in Sequence)
Or:
(expression for item in Sequence if conditional)
Tuple comprehensions work similarly to list comprehensions, but they use ()
parentheses, whereas list comprehensions use []
brackets. Additionally, tuple comprehensions return a generator object instead of a list.
Example: Generating a Tuple of Numbers from 1 to 9
>>> a = (x for x in range(1, 10)) >>> a <generator object <genexpr> at 0x7faf6ee20a50> # Returns a generator object >>> tuple(a) # Using the tuple() function converts the generator object into a tuple (1, 2, 3, 4, 5, 6, 7, 8, 9)