Intro to Comprehensions
The course is part of this learning path
In this course, we'll look at Comprehensions in Python. This course is part of a series of content designed to help you learn to program with the Python programming language.
- Describe the purpose of comprehensions
- Describe a list comprehension
- Describe a dictionary comprehension
- Describe a set comprehension
This course was designed for first-time developers wanting to learn Python.
This is an introductory course and doesn’t require any prior programming knowledge.
Hello, and welcome! My name is Ben Lambert, and I’ll be your instructor for this course. This course is part of a series of content designed to help you learn to program with the Python programming language.
Should you wish to ask me a specific question, you can do that with the contact details on screen. You can also reach support by using the email address: firstname.lastname@example.org. And one of our cloud experts will reply.
The Python runtime includes built-in objects which serve as a collection of other objects. The list, dictionary and set object types are so common that Python’s language syntax incorporated them into the language. By using the correct opening and closing brackets, we can define each of these in code. However, for these three types we can do more than just hard-code a list, set, or dictionary.
These types are so common that Python provides some additional syntax used to dynamically create new objects of these three types. This style of syntax is referred to as comprehensions. Comprehensions are a short-hand syntax which can replace certain for loops with a single line of code.
We’re going to cover three types of comprehension; list, dictionary, and set. Conceptually these are all the same. They’re just a short-hand syntax used to condense multiple lines of code into a single more readable line of code. I’m going to use list comprehensions to illustrate how comprehensions consolidate code. And then I’ll show the other two types.
Imagine that we have a list of strings. Each string contains the name of an interesting person to know. Now, imagine that we want to normalize all of these names to be titlecase. Here’s one way to solve this problem. We can bind a name to a new empty list.
This name: revised_people is currently empty. We need to loop through this list and for each person’s name we call the title method which will return a new string. We’ll append that string to this revised_people list. When the loop is done, this list will contain all the same people’s names only with title casing. Since lists maintain a sense of order, the new list matches the same order as the original.
This took a few lines of code. We create a new list and fill it with the modified objects. List comprehensions were created to make creating new lists easier by reducing the amount of code we need to write.
Let’s look at how we’d accomplish this using a list comprehension. We start out with the same list of people. We’ll talk about this syntax in a moment. For now, just know that this bit of code is a list comprehension. This line rebinds the name people_to_know to the list created by this comprehension.
List comprehensions loop through a collection and return an object for each iteration of the loop. Without focusing on the syntax you can see that this does in one line what we used a few lines to do previously. It’s very common for developers to need to produce a new collection based on values in an existing collection. In this case we’re transforming the text to be titlecase.
This is the purpose of comprehensions. Once you understand their syntax you’re able to use them to consolidate code into fewer - more expressive lines of code. Let’s go over the syntax for list comprehensions along with some examples. List comprehensions exist inside a pair of open and close square brackets. Notice that these are the same brackets used to create a list.
The first component of this syntax is the object that we want to include in the new list. Notice this says person.title - because we’re calling the title method of the string. The name person is bound in this for loop to the next object in the people_to_know list. This is similar to a regular for loop where we bind the name of the next object. This might feel a little backwards. After all we’re starting by using the name: person which is bound over to the right in the for loop. This will become familiar over time.
This syntax consolidated our code down from a few lines to just one. However, we can do even more with comprehensions. We can also include a condition. To the right of the comprehensions’ for loop we can use an if statement.
For example: we could filter the list down to only specific people. This is commonly used as a filter mechanism to remove unwanted objects from a list. Comprehensions can also be nested such that they loop over multiple lists. Here we have two lists which together define a US standard deck of cards. Imagine that we want to represent every single card. We can loop over each suit and each rank and produce a string representing all 52 cards.
Nesting comprehensions has some great use cases; however, it can also make code less readable when they become too complex. Let’s recap and make sure that the general idea of comprehensions is clear before we move on to dictionaries and sets. A comprehension is a short-hand syntax used to dynamically create a new collection. This enables us to transform the objects in the list and even filter them using conditions.
Let’s check out the syntax for dictionary comprehensions. Dictionary comprehensions use curly brackets - just as dictionaries do. Only rather than creating a new list - as list comprehensions do, these created new dictionaries. Imagine we have a dictionary which contains players of some game and their score.
Now imagine that we want to update all of the player’s scores to include a bonus for completing a level. Using a dictionary comprehension we can loop through each key and value and add the bonus points. Let’s look at the syntax a bit closer. Comparing this to list comprehensions we can see that it’s quite similar. The only difference is the brackets and that we’re returning a key and value. The key and value are joined by a colon.
Notice that we’re also binding two names in the for loop. The items method of a dictionary returns a tuple which includes the key and value. Python includes a feature called tuple unpacking which allows us to bind a name to each value in a tuple. That’s what you’re seeing here. This isn’t specific to dictionary comprehensions.
Just like list comprehensions, dictionary comprehensions are able to use conditions. To the right of the for loop we can define a condition using an if statement. Let’s take a look at our final comprehension which is the set comprehension. Imagine that our list of people to know includes repeated names, with different letter cases. We want to remove any duplicates. Using a set comprehension, we can loop through each and convert it into title-case. Since this produces a set, the results will be unique.
The syntax for set comprehensions uses curly brackets - and only returns a single object for each pass through the loop. Conceptually all of these comprehensions are similar. They all include at least one for loop - though, they can be nested. And they can each be filtered using conditions. Don’t feel that you need to memorize all of this syntax. You’ll pick it up when you have a need to use it. Just knowing that these exist will help you to get started. Since you’ll likely see them in other people’s code.
Okay, this seems like a natural stopping point. Here are your key takeaways for this lesson:
- Comprehensions are a short-hand syntax which can replace certain for loops with a single line of code. And they can be nested and or conditional.
- List comprehensions are used to create a new list based on the data in another collection.
- Dictionary comprehensions are used to create a new dictionary based on the data in another collection.
- Set comprehensions are used to create a new set based on the data in another collection.
Alright, that's all for this lesson. Thanks so much for watching. And I’ll see you in another lesson!
Ben Lambert is a software engineer and was previously the lead author for DevOps and Microsoft Azure training content at Cloud Academy. His courses and learning paths covered Cloud Ecosystem technologies such as DC/OS, configuration management tools, and containers. As a software engineer, Ben’s experience includes building highly available web and mobile apps. When he’s not building software, he’s hiking, camping, or creating video games.