Can I use assignment operators as expression in python list comprehension?

Related Questions
- Python Assignment Expression In List Comprehension Pdf
Python Assignment Expression In List Comprehension Pdf latest celeb news, photos and stories about Python Assignment Expression In List Comprehension PdfThe Walrus Operator can be used in list comprehensions so that a function doesn't have to be called multiple times.

Python 3.8 Walrus Operator (Assignment Expression) - Finxter

[PDF] List Comprehensions
![python assignment expression in list comprehension [PDF] List Comprehensions](https://celebdailyposts.com/public/icons/placeholder.png)
When to Use a List Comprehension in Python

The Walrus Operator: Python 3.8 Assignment Expressions

How To Use Assignment Expressions in Python | DigitalOcean

Python List Comprehension - Learn By Example

Assignment operator in list comprehension Python - Cùng Hỏi Đáp

Python List Comprehension - Intellipaat

PEP 572 – Assignment Expressions

Python List Comprehension Tutorial - DataCamp

Python Language Tutorial => Conditional List Comprehensions
The do's and don'ts of python list comprehension - better ....

PEP 572 and The Walrus Operator — pysheeet

if else in list comprehension python Code Example

Python List Comprehension | Benefits, Syntax and Examples of ...

List Comprehensions in Python - PythonForBeginners.com

Comparison of programming languages (list comprehension)

How can I do assignments in a list comprehension? - Stack Overflow

eng2spkeys one three two 18Define List Comprehension List ...


Trending Now
Saddest Shortest Story 4,374,810
Always Keep your eyes on the road, your hands upon the wheel 1,748,311
Moment My Heart Will Go On 1,525,567
So Candy 1,343,317
Business Management Courses: Top 5 Online Business Certificates To Advance Your Career 1,241,647
That’s level of not getting hints 857,467
Myuhcmedicare HWP Catalog Online 389,919
When the favorite song comes on 374,434
Traditions 317,280
Lucky Bus Driver 50,062
Popular Search
- Python walrus operator list comprehension
- Python assignment PDF
- Python assignment examples
- Python assignment in if
- Python assignments for practice
- Python walrus operator if statement
- Python walrus operator for loop
- Assignment expression in C
Recent Search
- ny news live
- Catholic News Service
- Los Angeles Chargers News
- tal education news celeb
- gavin newsom celeb
- euro 2021 predictions reddit today news
- tennis news now wiki
- hikvision banned in india 2019 news
- hans f1 news
- cdc cruise news
- hsbc holdings news celeb
- washington weekly news quiz
- hr news 2021
- tulsa news 8
- youtube hiru news today
- wtkr local news channel 3
- wisconsin football news 2021
- wisconsin badger football news and recruiting
Python3.8 assignment expressions, use in list comprehension or as an expression
I recently discovered that assignment expressions exist. And I wanted to refactor some of my code to make use of them. Most of the places I wanted to use it were relatively straightforward to convert.
However, I'm not sure of the syntax to use for this particular function. Is there a way I could replace my usage of functools.reduce with assignment expressions?
It's not straightforward to me how to use the result of an assignment expression as an expression directly. Is there a nice and pythonic way to do this?
You don't need assignment expressions here, see this simple list comprehension:
Thanks, that certainly solves my "I make awful code at 4AM" problem. But I am still curious as to whether or not it is possible to use an assignment expression in this way. If you like I can come up with a better example.
@OmnipotentEntity yes, please do, I'd be happy to have a look ;) (maybe get some rest before, sleep is important :p)
Or not, it seem like it will not let me. Ah well, in that case I'll edit this question in the morning if it's still bothering me.
How to Use Assignment Expressions in Python

Many languages support assignment expressions , and with version 3.8 ( PEP 572 ), Python is joining the party. Assignment expressions allow us to name the result of expressions, which results in cleaner, more concise code.
Previously, this was only possible in statement form, like this:
Assignment expressions, however, allow us to avoid the statement, and assign the value of result right in the conditional expression.
Why is is called the "walrus operator"?
Well, because it looks like a walrus! :=
Now that we've covered the basics, I'll provide some examples where assignment expressions might prove useful.

Regular expression matching
When using regular expressions, we often want to test for a match first , then, if they exist, do something with them.
While loops
Sometimes when we use while loops we need to compute a value to determine when to terminate the loop. Previously, the assignment would've been a separate statement (actually two, one before the loop and one within). But using the walrus operator we can simplify our code quite a bit.
Comprehensions
Another brilliant use case for assignment expressions is within list comprehensions. Sometimes, when we need to compute something inside the filtering condition, we also want to use the computed value in the expression body. This is especially valuable when the computation is expensive.
In the above example, we want to process the item before using it in the conditional. Using an assignment expression allows us to do this, and then use the resulting value in the comprehension body.
If you're familiar with Python's keyword-only arguments, then you've probably wondered why the same constraint doesn't exist for positional arguments. This changes with Python 3.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Assignments in python list comprehension
I am looking for a way to do assignments in a list comprehension. I would like to rewrite something like the following piece of code into a list comprehension.
I have this "costly" function:
And this loop:
I would like to rewrite this to a list comprehension:
But since calling f(value) is costly, I would like to minimize the number of calls (this following snippet doesn't run):
I've read about the assignment expression ( := ) ( https://www.python.org/dev/peps/pep-0572/#changing-the-scope-rules-for-comprehensions ) but I can't seem to figure it out.
- list-comprehension
- For the given example, does l = [x*10 for x in [1, 2, 3]] work? – arshovon Jan 16, 2022 at 13:12
- Does this answer your question? How can I do assignments in a list comprehension? – Hector Haffenden Jan 16, 2022 at 13:14
- Does not work! x, y = f(value) requires f to return an iterable of 2 values, while your example only return a scalar. – Serge Ballesta Jan 16, 2022 at 13:48
- After a second look,I think that you wanted ... return x, x+1 – Serge Ballesta Jan 16, 2022 at 13:54
3 Answers 3
My approach would be to nest multiple list comprehension, like
So f() should only be called once for each value.
- Thank you for your answer. The problem for me would be that we introduce an extra loop which makes it a bit unreadable to me – Steven Jan 16, 2022 at 17:52
Here is another way to fake it:
This can be done with a walrus operator. Note that you need Python 3.8 or later.
With one fast and slow function.
The walrus operator can be skipped in both these examples, but perhaps the real problem would require it.
- I think you don’t even need walrus assignment here, right? – rv.kvetch Jan 16, 2022 at 13:15
- Yeah for the original example I made this is true. I updated the post to demonstrate my problem more clearly. – Steven Jan 16, 2022 at 13:22
- In that case you could write one fast and one slow function, like this. – liveware Jan 16, 2022 at 16:14
- What would be the use of the walrus operator? Since x is not (re-)used – Steven Jan 16, 2022 at 16:23
- 1 You could write it as e.g. l = [(x := f(value), x + x)[1] for value in [1, 2, 3]] , if you're willing to create a tuple and take the second element of it inside the list comprehension. – liveware Jan 16, 2022 at 19:06
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged python python-3.x list-comprehension or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- How to follow the signal when reading the schematic?
- What sort of strategies would a medieval military use against a fantasy giant?
- The region and polygon don't match. Is it a bug?
- About an argument in Famine, Affluence and Morality
- Calculating probabilities from d6 dice pool (Degenesis rules for botches and triggers)
- What video game is Charlie playing in Poker Face S01E07?
- If you preorder a special airline meal (e.g. vegan) just to try it, does this inconvenience the caterers and staff?
- Checking system vs. SEPA and the like
- better way to photograph a LED wall (people dancing in front of it)
- What is the correct way to screw wall and ceiling drywalls?
- A-Z related to countries
- Applications of super-mathematics to non-super mathematics
- Are there tables of wastage rates for different fruit and veg?
- How do you get out of a corner when plotting yourself into a corner
- Is lock-free synchronization always superior to synchronization using locks?
- "We, who've been connected by blood to Prussia's throne and people since Düppel"
- Why is there a voltage on my HDMI and coaxial cables?
- Who owns code in a GitHub organization?
- Is it suspicious or odd to stand by the gate of a GA airport watching the planes?
- Did any DOS compatibility layers exist for any UNIX-like systems before DOS started to become outmoded?
- Theoretically Correct vs Practical Notation
- Minimising the environmental effects of my dyson brain
- Does Counterspell prevent from any further spells being cast on a given turn?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

When to Use a List Comprehension in Python
Table of Contents
Using for Loops
Using map() objects, using list comprehensions, benefits of using list comprehensions, using conditional logic, using set and dictionary comprehensions, using the walrus operator, watch out for nested comprehensions, choose generators for large datasets, profile to optimize performance.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Understanding Python List Comprehensions
Python is famous for allowing you to write code that’s elegant, easy to write, and almost as easy to read as plain English. One of the language’s most distinctive features is the list comprehension , which you can use to create powerful functionality within a single line of code. However, many developers struggle to fully leverage the more advanced features of a list comprehension in Python. Some programmers even use them too much, which can lead to code that’s less efficient and harder to read.
By the end of this tutorial, you’ll understand the full power of Python list comprehensions and how to use their features comfortably. You’ll also gain an understanding of the trade-offs that come with using them so that you can determine when other approaches are more preferable.
In this tutorial, you’ll learn how to:
- Rewrite loops and map() calls as a list comprehension in Python
- Choose between comprehensions, loops, and map() calls
- Supercharge your comprehensions with conditional logic
- Use comprehensions to replace filter()
- Profile your code to solve performance questions
Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.
How to Create Lists in Python
There are a few different ways you can create lists in Python. To better understand the trade-offs of using a list comprehension in Python, let’s first see how to create lists with these approaches.
The most common type of loop is the for loop. You can use a for loop to create a list of elements in three steps:
- Instantiate an empty list.
- Loop over an iterable or range of elements.
- Append each element to the end of the list.
If you want to create a list containing the first ten perfect squares, then you can complete these steps in three lines of code:
Here, you instantiate an empty list, squares . Then, you use a for loop to iterate over range(10) . Finally, you multiply each number by itself and append the result to the end of the list.
map() provides an alternative approach that’s based in functional programming . You pass in a function and an iterable, and map() will create an object. This object contains the output you would get from running each iterable element through the supplied function.
As an example, consider a situation in which you need to calculate the price after tax for a list of transactions:
Here, you have an iterable txns and a function get_price_with_tax() . You pass both of these arguments to map() , and store the resulting object in final_prices . You can easily convert this map object into a list using list() .
List comprehensions are a third way of making lists. With this elegant approach, you could rewrite the for loop from the first example in just a single line of code:
Rather than creating an empty list and adding each element to the end, you simply define the list and its contents at the same time by following this format:
Every list comprehension in Python includes three elements:
- expression is the member itself, a call to a method, or any other valid expression that returns a value. In the example above, the expression i * i is the square of the member value.
- member is the object or value in the list or iterable. In the example above, the member value is i .
- iterable is a list, set , sequence, generator , or any other object that can return its elements one at a time. In the example above, the iterable is range(10) .
Because the expression requirement is so flexible, a list comprehension in Python works well in many places where you would use map() . You can rewrite the pricing example with its own list comprehension:
The only distinction between this implementation and map() is that the list comprehension in Python returns a list, not a map object.
List comprehensions are often described as being more Pythonic than loops or map() . But rather than blindly accepting that assessment, it’s worth it to understand the benefits of using a list comprehension in Python when compared to the alternatives. Later on, you’ll learn about a few scenarios where the alternatives are a better choice.
One main benefit of using a list comprehension in Python is that it’s a single tool that you can use in many different situations. In addition to standard list creation , list comprehensions can also be used for mapping and filtering. You don’t have to use a different approach for each scenario.
This is the main reason why list comprehensions are considered Pythonic , as Python embraces simple, powerful tools that you can use in a wide variety of situations. As an added side benefit, whenever you use a list comprehension in Python, you won’t need to remember the proper order of arguments like you would when you call map() .
List comprehensions are also more declarative than loops, which means they’re easier to read and understand. Loops require you to focus on how the list is created. You have to manually create an empty list, loop over the elements, and add each of them to the end of the list. With a list comprehension in Python, you can instead focus on what you want to go in the list and trust that Python will take care of how the list construction takes place.
How to Supercharge Your Comprehensions
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 are coming to the list comprehension in Python 3.8 .
Earlier, you saw this formula for how to create list comprehensions:
While this formula is accurate, it’s also a bit incomplete. 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.
Conditionals are important because they allow list comprehensions to filter out unwanted values, which would normally require a call to filter() :
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. 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 is_consonant() and pass this function as the conditional statement for your list comprehension. 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, 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 near the beginning of the expression:
With this formula, you can use conditional logic to select from multiple possible output options. 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 . 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. If this seems overwhelming, then it may be helpful to view the conditional logic as its own function:
Now, your conditional statement is contained within get_price() , and you can use it as part of your list comprehension expression.
While the list comprehension in Python is a common tool, you can also create set and dictionary comprehensions. A set comprehension is almost exactly the same as a list comprehension in Python. The difference is that set comprehensions make sure the output contains no duplicates. You can create a set comprehension by using curly braces instead of brackets:
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. This is why the first member of the set is a , even though the first vowel in quote is i .
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.
Python 3.8 will introduce the assignment expression , also known as the walrus operator . To understand how you can use it, consider the following example.
Say you need to make ten requests to an API that will return temperature data. You only want to return results that are greater than 100 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. 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. It allows you to run an expression while simultaneously assigning the output value to a variable. The following example shows how this is possible, using get_weather_data() 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.
When Not to Use a List Comprehension in Python
List comprehensions are useful and can help you write elegant code that’s easy to read and debug, but they’re not the right choice for all circumstances. They might make your code run more slowly or use more memory. If your code is less performant or harder to understand, then it’s probably better to choose an alternative.
Comprehensions can be nested to create combinations of lists, dictionaries, and sets within a collection. For example, say a climate laboratory is tracking the high temperature in five different cities for the first week of June. The perfect data structure for storing this data could be a Python list comprehension nested within a dictionary comprehension:
You create the outer collection temps with a dictionary comprehension. The expression is a key-value pair, which contains yet another comprehension. This code will quickly generate a list of data for each city in cities .
Nested lists are a common way to create matrices , which are often used for mathematical purposes. Take a look at the code block below:
The outer list comprehension [... for _ in range(6)] creates six rows, while the inner list comprehension [i for i in range(5)] fills each of these rows with values.
So far, the purpose of each nested comprehension is pretty intuitive. However, there are other situations, such as flattening nested lists, where the logic arguably makes your code more confusing. Take this example, which uses a nested list comprehension to flatten a matrix:
The code to flatten the matrix is concise, but it may not be so intuitive to understand how it works. On the other hand, if you were to use for loops to flatten the same matrix, then your code will be much more straightforward:
Now you can see that the code traverses one row of the matrix at a time, pulling out all the elements in that row before moving on to the next one.
While the single-line nested list comprehension might seem more Pythonic, what’s most important is to write code that your team can easily understand and modify. When you choose your approach, you’ll have to make a judgment call based on whether you think the comprehension helps or hurts readability.
A list comprehension in Python works by loading the entire output list into memory. For small or even medium-sized lists, this is generally fine. If you want to sum the squares of the first one-thousand integers, then a list comprehension will solve this problem admirably:
But what if you wanted to sum the squares of the first billion integers? If you tried then on your machine, then you may notice that your computer becomes non-responsive. That’s because Python is trying to create a list with one billion integers, which consumes more memory than your computer would like. Your computer may not have the resources it needs to generate an enormous list and store it in memory. If you try to do it anyway, then your machine could slow down or even crash.
When the size of a list becomes problematic, it’s often helpful to use a generator instead of a list comprehension in Python. A generator doesn’t create a single, large data structure in memory, but instead returns an iterable. Your code can ask for the next value from the iterable as many times as necessary or until you’ve reached the end of your sequence, while only storing a single value at a time.
If you were to sum the first billion squares with a generator, then your program will likely run for a while, but it shouldn’t cause your computer to freeze. The example below uses a generator:
You can tell this is a generator because the expression isn’t surrounded by brackets or curly braces. Optionally, generators can be surrounded by parentheses.
The example above still requires a lot of work, but it performs the operations lazily . Because of lazy evaluation, values are only calculated when they’re explicitly requested. After the generator yields a value (for example, 567 * 567 ), it can add that value to the running sum, then discard that value and generate the next value ( 568 * 568 ). When the sum function requests the next value, the cycle starts over. This process keeps the memory footprint small.
map() also operates lazily, meaning memory won’t be an issue if you choose to use it in this case:
It’s up to you whether you prefer the generator expression or map() .
So, which approach is faster? Should you use list comprehensions or one of their alternatives? Rather than adhere to a single rule that’s true in all cases, it’s more useful to ask yourself whether or not performance matters in your specific circumstance. If not, then it’s usually best to choose whatever approach leads to the cleanest code!
If you’re in a scenario where performance is important, then it’s typically best to profile different approaches and listen to the data. timeit is a useful library for timing how long it takes chunks of code to run. You can use timeit to compare the runtime of map() , for loops, and list comprehensions:
Here, you define three methods that each use a different approach for creating a list. Then, you tell timeit to run each of those functions 100 times each. timeit returns the total time it took to run those 100 executions.
As the code demonstrates, the biggest difference is between the loop-based approach and map() , with the loop taking 50% longer to execute. Whether or not this matters depends on the needs of your application.
In this tutorial, you learned how to use a list comprehension in Python to accomplish complex tasks without making your code overly complicated.
Now you can:
- Simplify loops and map() calls with declarative list comprehensions
- Create set and dictionary comprehensions
- Determine when code clarity or performance dictates an alternative approach
Whenever you have to choose a list creation method, try multiple implementations and consider what’s easiest to read and understand in your specific scenario. If performance is important, then you can use profiling tools to give you actionable data instead of relying on hunches or guesses about what works the best.
Remember that while Python list comprehensions get a lot of attention, your intuition and ability to use data when it counts will help you write clean code that serves the task at hand. This, ultimately, is the key to making your code Pythonic!
🐍 Python Tricks 💌
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

About James Timmins

James is a software consultant and Python developer. When he's not writing Python, he's usually writing about it in blog or book form.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!
Keep Learning
Related Tutorial Categories: basics python
Recommended Video Course: Understanding Python List Comprehensions
Keep reading Real Python by creating a free account or signing in:
Already have an account? Sign-In
Almost there! Complete this form and click the button below to gain instant access:

"Python Tricks: The Book" – Free Sample Chapter (PDF)
🔒 No spam. We take your privacy seriously.

IMAGES
VIDEO
COMMENTS
I'm trying to use the new assignment expression for the first time and could use some help. Given three lines of log outputs:sin = ""Writing 93 records to /data/newstates-900.03-07_07/top100
LoginQandeel Academy | Viewed 8 times | 2 months ago. Subscribe to the mailing list
Latest Python Assignment Expression In List Comprehension Pdf updated Dec-2021. Celeb News by Python Assignment Expression In List Comprehension Pdf. Aug 9, 2021 — In this tutorial, you'll learn about assignment expressions and the walrus
class Solution: def maxSatisfaction( self, satisfaction: List[ int]) -> int: satisfaction.sort() margin = ans = 0 [ans:= ans + margin for val in reversed(satisfaction) if (margin:=val+margin) > 0] return ans
python Python3.8 assignment expressions, use in list comprehension or as an expression I recently discovered that assignment expressions exist
Another brilliant use case for assignment expressions is within list comprehensions. Using an assignment expression allows us to do this, and then use the resulting value in the comprehension body
I am looking for a way to do assignments in a list comprehension. I would like to rewrite something like the following piece of code into a list comprehension