Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

How to Supercharge Your Comprehensions

00:00 In order to understand the full value that list comprehensions can provide, it’s helpful to understand their range of possible functionality. You’ll also want to understand the changes that were made to list comprehension in Python 3.8, so we’ll cover these also. Firstly, let’s look at using conditional logic. In the previous lesson, you saw this formula for how to create list comprehensions. While this formula is accurate, it’s also a bit incomplete.

00:28 A more complete description of the comprehension formula adds support for optional conditionals. The most common way to add conditional logic to a list comprehension is to add a conditional to the end of the expression. Here, your conditional statement comes just before the closing bracket.

00:49 Conditionals are important because they allow list comprehensions to filter out unwanted values, which would normally require a call to the filter() function.

00:58 Let’s have a look at an example. In this code block, the conditional statement filters out any characters in sentence that aren’t a vowel. The conditional can test any valid expression.

01:11 If you need a more complex filter, then you can even move the conditional logic to a separate function. Here you create a complex filter called is_consonant() and pass this function as the conditional statement for your list comprehension.

01:26 Note that the member value i is also passed as an argument to your function. You can place the conditional at the end of the statement for simple filtering.

01:38 But what if you want to change a member value instead of filtering it out? In this case, it’s useful to place the conditional at the beginning of the expression.

01:48 With this formula, you can use conditional logic to select from multiple possible output options.

01:56 For example, if you have a list of prices, then you may want to replace negative prices with 0 and leave the positive values unchanged. Here, your expression i contains a conditional statement, if i > 0 else 0.

02:12 This tells Python to output the value of i if the number is positive, but to change i to 0 if the number is negative.

02:21 If this seems overwhelming, then it may be helpful to view the conditional logic as its own function.

02:28 Now your conditional statement is contained within the get_price() function, and you can use it as part of your list comprehension expression.

02:39 While the list comprehension in Python is a common tool, you can also create sets and dictionary comprehensions. A set comprehension is almost exactly the same as a list comprehension in Python.

02:51 The difference is that the comprehensions make sure that the output contains no duplicates. You can create a set comprehension by using curly braces instead of brackets.

03:03 Your set comprehension outputs all the unique vowels it found in quote. Unlike lists, sets don’t guarantee that items will be saved in any particular order.

03:15 Dictionary comprehensions are similar, with the additional requirement of defining a key. To create the squares dictionary, you use curly braces as well as a key-value pair, i: i * i in your expression.

03:34 Python 3.8 introduced the assignment expression, also known as the walrus operator. It allows you to run an expression while simultaneously assigning the output value to a variable. To understand how you can use it, let’s have a look at an example.

03:51 Say that we need to make ten requests to an API that will return temperature data. You only want to return results that are greater than a hundred degrees Fahrenheit. Assume that each request will return different data. In this case, there’s no way to use a list comprehension in Python to solve the problem.

04:08 The formula expression for member in iterable if conditional provides no way for the conditional to assign data to a variable that the expression can access. The walrus operator solves this problem.

04:21 As I already mentioned, it allows you to run an expression while simultaneously assigning the output value to a variable. Let’s have a look at this in an example.

04:31 In this case, we’re going to use the get_weather_data() function to generate fake weather data. You won’t often need to use the assignment expression inside of a list comprehension in Python, but it’s a useful tool to have at your disposal when necessary.

04:47 So now you know how to supercharge your list comprehensions and how useful they can be, but it’s also important to understand that there are certain circumstances in which they are not the right choice. In the next lesson, you’ll learn when not to use a list comprehension in Python.

Brandon Hopkins on April 13, 2023

Way too fast and the examples used could have been so much simpler. Had to use chatGPT to get me through this one.

praghavan1973 on June 7, 2023

what is the meaning of _ in

hot_tenps = [temp for _ in range(20) if (…)]

praghavan1973 on June 7, 2023

Got the meaning of _.

Looks like we are not interested in the outcome of the range. We just want to call the function get_weather_data() 20 times. So _ is used as a dont care variable.

Had to find that out from the net.

It would have been nicer if instructore went thru syntax of the code and explained it in brief.

alnah on Sept. 23, 2023

Hi everybody! ✌️

If it can help, Richi is using three syntaxes:

Basic List Comprehension:

new_list = [<expression> for <element> in <iterable>]

This is the basic syntax of a list comprehension, which defines the list and its content.

List Comprehension with Condition:

new_list_2 = [<expression> for <element> in <iterable> if <condition>]

This syntax will add the element to the list only if the condition is True. If the condition is False, the element will not be added to the list.

List Comprehension with If-Else Conditional Statement:

new_list_3 = [<expression_if_true> if <condition> else <expression_if_false> for <element> in <iterable>]

This one might be harder to understand due to the use of the if-else conditional statement. The list comprehension evaluates the condition for each element in the iterable. If the condition is True, it evaluates and appends the <expression_if_true> to the new list; otherwise, it evaluates and appends the <expression_if_false>.

Become a Member to join the conversation.