Comprehensions

Learn about the concept of list comprehensions and their mapping in Python.

We'll cover the following

Comprehensions are simple, but powerful, syntaxes that allow us to transform or filter an iterable object in as little as one line of code. The resultant object can be a perfectly normal list, set, or dictionary, or it can be a generator expression that can be efficiently consumed while keeping just one element in memory at a time.

List comprehensions

List comprehensions are one of the most powerful tools in Python, so people tend to think of them as advanced. They’re not. Indeed, we’ve taken the liberty of littering previous examples with comprehensions. While it’s true that advanced programmers use comprehensions a lot, it’s not because they’re advanced. It’s because a comprehension is so fundamental to Python, it can handle many of the most common operations in application software.

Let’s have a look at one of those common operations; namely, converting a list of items into a list of related items. Specifically, let’s assume we just read a list of strings from a file, and now we want to convert it to a list of integers. We know every item in the list is an integer, and we want to do some activity (say, calculate an average) on those numbers. Here’s one simple way to approach it:

Get hands-on with 1200+ tech skills courses.