Published on 2017-12-30
2 min read
Let's talk Python. Basics. List comprehension is a vital part of many Python scripts. It allows - in plain English - a programmer to build a list out of another list (or even other lists) in a very concise way. Python 3 has introduced the capabilities to apply comprehension to dictionaries and sets as well.
The fundamental idea of comprehension is to apply a given expression to each element of a list, a set or a dictionary (an iterable). Sounds familiar, if you think about the concept behind map, reduce and filter. In Python, an actual list comprehension looks this:
[ <expression> for <element> in <iterable> ]
This rather basic form can be extended to include a condition checked against each element of the iterable as well.
[ <expression> for <element> in <iterable> if <condition_applied_to_element> ]
If you need an
else statement as well move the condition to the front like so:
[ <expression> if <condition_applied_to_element> else <statement> for <element> in <iterable> ]
We have seen how comprehension works in theory. Let's use each of the three discussed options in a quick example.
To get started we add 1 to a list of numbers.
list_of_numbers = [23, 45, 62, 88] added_one = [number + 1 for number in list_of_numbers] print(added_one) # prints [24, 46, 63, 89]
How about we take only even numbers out of our list of numbers and multiply them by two?
list_of_numbers = [23, 45, 62, 88] even_ones = [number * 2 for number in list_of_numbers if number % 2 == 0 ] print(even_ones) # prints [124, 176]
Finally, we square the odd ones and replace the even numbers with
list_of_numbers = [23, 45, 62, 88] squared_and_replaced = [number * 2 if number % 2 != 0 else 'foo' for number in list_of_numbers ] print(squared_and_replaced) # prints [46, 90, 'foo', 'foo']
That's it with a quick and easy introduction to comprehension in Python. The simple examples just scratched the surface of what can be accomplished with comprehension. Give it a try the next time you are thinking about iterating over each element of a list.