Python List, Tuple, Set, and Dictionary Comprehensions

Python is known for its clean, concise, English-like syntax. However, not all code lives up to this expectation. For example, it is common to write things like the following:
cats = []
for animal in animals:
    if type(animal) is Cat:
        cats.append(animal)


That works, and gives the expected result, but is a bit long. With a list comprehension (a construct that combines iterator assignment with a for loop), the above code would look more like this:
cats = [ animal for animal in animals if type(animal) is Cat ].

Much more concise.

List comprehensions

Here's the format for a list comprehension:
[ output for input_item in input_iterable if condition ]

Here's another example:
>>> squares_of_evens = [ number**2 for number in range(0, 11) if number%2 == 0]
>>> squares_of_evens
[0, 4, 16, 36, 64, 100]


The alternative would be:
>>> squares_of_evens = []
>>> for number in range(0, 11):
...     if number%2 == 0:
...         squares_of_evens.append(number**2)
...
>>> squares_of_evens
[0, 4, 16, 36, 64, 100]


It works, but the version with the comprehension is a lot more concise.

In list comprehensions and all the other comprehensions, the "if condition" part is optional. For example:

>>> squares_of_all = [ number**2 for number in range(0, 11) ]
>>> squares_of_all
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Tuple and Set Comprehensions

Tuple and set comprehensions are very similar. Just replace the [ and ] with ( and ) for a tuple comprehension or { and } for a set comprehension. Note that list, tuple, and set comprehensions can all work on any iterable; the type only determines the output. For example, { item*2 for item in [1, 2, 3] } will work fine; the set comprehension can work on a list.

Tuple comprehension:
( output for input_item in input_iterable if condition )

Set comprehension:
{ output for input_item in input_iterable if condition }

Dictionary Comprehensions

Dictionary (dict) comprehensions are a bit more complicated. Their general format is:
{ output_key:output_value for (input_key, input_value) in input_tuple_list if condition }

input_tuple_list is a list of tuples of two items, each a key/value pair. The dict {'a': 'b', 'c': 'd'} would become [ ('a', 'b'), ('c', 'd') ]. Dictionaries have a method, .items(), that automates this.

Here's an example:
>>> ages = {'Bob': 20, 'Emma': 16, 'Jane': 24, 'James': 49, 'Mary': 73, 'Betty': 101}
>>> years_till_100 = { name: 100-age for (name, age) in ages.items() if age < 100 }
>>> years_till_100
{'Bob': 80, 'Emma': 84, 'Jane': 76, 'James': 51, 'Mary': 27}


The non-comprehension version would look like this:
>>> ages = {'Bob': 20, 'Emma': 16, 'Jane': 24, 'James': 49, 'Mary': 73, 'Betty': 101}
>>> years_till_100 = {}
>>> for (name, age) in ages.items():
...     if age < 100:
...         years_till_100[name] = 100-age
...
>>> years_till_100
{'Bob': 80, 'Emma': 84, 'Jane': 76, 'James': 51, 'Mary': 27}


Once again, the version with the comprehension is more concise.

Overall, comprehensions are a way to make your code shorter and more Pythonic without losing functionality. While they are never technically necessary, they can greatly improve code quality.

Comments

Popular posts from this blog

Why app auto-updates (on any platform) are an absolute necessity

Samsung Chromebook Plus V2 Review