List comprehensions provide you with a “concise way to create lists”, according to the official docs, but they do a lot more than that. They’re a great feature of Python; let’s do a few examples to illustrate why.
List comprehension as a map function
my_list = [1, 2, 3]
doubled = [num * 2 for num in my_list]
# [2, 4, 6]
The example above is the same as using a map
function in other languages, but more concise. You can also replicate filter
with list comprehensions.
List comprehension as a filter function
my_list = [1, 2, 3]
odds = [num for num in my_list if num % 2 != 0]
# [1, 3]
Python does have builtins for map
and filter
, but I almost always find myself using list comprehensions instead; they’re shorter and much more pythonic.
If you have more complicated logic you can do something like this:
new_list = [complicated_function(i) for i in old_list]
# when you have a filter function
filtered_list = [i for i in old_list if complicated_filter(i)]
All of the examples above can equally be written as traditional for in
loops, but list comprehension syntax is very commonly-used in Python; you’ll see it everywhere.
That said, list comprehensions certainly are not a drop-in replacement for traditional for loops, and if you have to perform multiple operations during a loop, or you need to add a nice explainer comment, you might need an old-school for
.
List Comprehensions for other types
The name “list” comprehension is a bit of a misnomer, the syntax functions on anything iterable
in Python: lists, dicts, sets, tuples, even strings. Since we already covered lists above, let’s do some examples with other iterable types.
Dicts
List comprehensions are commonly used in combination with dict.items()
to invert a Python dictionary:
my_dict = {"a": 1, "b":2}
{value: key for key, value in my_dict.items()}
# {1: "a", 2: "b"}
Sets
Loop over items and create a set:
my_list = [1, 2, 3, 4]
# pluck out odd values and build a new set
my_set = {val for val in my_set if val % 2 != 0}
# {1, 3}
type(my_set) # set
Tuples
Pluck out a single value from a list of tuples:
list_of_tuples = [('nic', 'cage'), ('tom', 'hanks')]
first_names = [a for (a, b) in list_of_tuples]
# ['nic', 'tom']
Conclusion
List comprehensions are one of the features that make Python my personal favorite language to work in. They’re very concise, and they make it easy to work with and convert between all of Python’s iterable types.
Helpful Links
- List Comprehensions – Python official docs
- Python Iterables
- Python For Loops – Me