Python walrus operator if statement
Each new version of Python adds new features to the language. For Python 3.8, the biggest change is the addition of assignment expressions. Specifically, the Show
This tutorial is an in-depth introduction to the walrus operator. You will learn some of the motivations for the syntax update and explore some examples where assignment expressions can be useful. In this tutorial, you’ll learn how to:
Note that all walrus operator examples in this tutorial require Python 3.8 or later to work. Walrus Operator FundamentalsLet’s start with some different terms that programmers use to refer to this new syntax. You’ve already seen a few in this tutorial. The Hello, Walrus!To get a first impression of what assignment expressions are all about, start your REPL and play around with the following code: >>>
Line 1 shows a traditional assignment statement where the value You might be wondering why you’re using parentheses on line 5, and you’ll learn why the parentheses are needed later on in this tutorial. There’s a subtle—but important—difference between the two types of assignments seen earlier with the You can see another important aspect about walrus operators in this example. Though it might look new, the Now you have a basic idea of what the ImplementationLike most new features in Python, assignment expressions were introduced through a Python Enhancement Proposal (PEP). PEP 572 describes the motivation for introducing the walrus operator, the details of the syntax, as well as examples where the This PEP was originally written by Chris Angelico in February 2018. Following some heated discussion, PEP 572 was accepted by Guido van Rossum in July 2018. Since then, Guido announced that he was stepping down from his role as benevolent dictator for life (BDFL). Starting in early 2019, Python has been governed by an elected steering council instead. The walrus operator was implemented by Emily Morehouse, and made available in the first alpha release of Python 3.8. MotivationIn many languages, including C and its derivatives, assignment statements function as expressions. This can be both very powerful and also a source of confusing bugs. For example, the following code is valid C but doesn’t execute as intended:
Here, The problem is that you’re using the assignment operator ( Take a look at a corresponding example in Python. This code raises a
Unlike the C example, this Python code gives you an explicit error instead of a bug. The distinction between assignment statements and assignment expressions in Python is useful in order to avoid these kinds of hard-to-find bugs. PEP 572 argues that Python is better suited to having different syntax for assignment statements and expressions instead of turning the existing assignment statements into expressions. One design principle underpinning the walrus operator is that there are no identical code contexts
where both an assignment statement using the >>>
In many cases, you can add parentheses ( >>>
Writing a traditional assignment statement with Later on in this tutorial, you’ll learn more about situations where the walrus operator is not allowed, but first you’ll learn about the situations where you might want to use them. Walrus Operator Use CasesIn this section, you’ll see several examples where the walrus operator can simplify your code. A general theme in all these examples is that you’ll avoid different kinds of repetition:
You’ll see how the walrus operator can help in each of these situations. DebuggingArguably one of the best use cases for the walrus operator is when debugging complex expressions. Say that you want to find the distance between two locations along the earth’s surface. One way to do this is to use the haversine formula: ϕ represents the latitude and λ represents the longitude of each location. To demonstrate this formula, you can calculate the distance between Oslo (59.9°N 10.8°E) and Vancouver (49.3°N 123.1°W) as follows: >>>
As you can see, the distance from Oslo to Vancouver is just under 7200 kilometers. Now, say that you need to double-check your implementation and want to see how much the haversine terms contribute to the final result. You could copy and paste the term from your main code to evaluate it separately.
However, you could also use the >>>
The advantage of using the walrus operator here is that you calculate the value of the full expression and keep track of the value of Lists and DictionariesLists are powerful data structures in Python that often represent a series of related attributes. Similarly, dictionaries are used all over Python and are great for structuring information. Sometimes when setting up these data structures, you end up performing the same operation several times. As a first example, calculate some basic descriptive statistics of a list of numbers and store them in a dictionary: >>>
Note that both the sum and the length of the >>>
The variables >>>
In the next example, you’ll work with a bare-bones implementation of the
This script can read one or several text files and report how many lines, words, and characters each of them contains. Here’s a breakdown of what’s happening in the code:
To see
In other words, the If you look closely
at this implementation, you’ll notice that it’s far from optimal. In particular, the call to
The contents of the file are assigned to
As in the earlier examples, an alternative approach is to define
While this is one line longer than the previous implementation, it probably provides the best balance between readability and efficiency. The List ComprehensionsList comprehensions are great for constructing and filtering lists. They clearly state the intent of the code and will usually run quite fast. There’s one list comprehension use case where the walrus operator can be particularly useful. Say that you want to apply some
computationally expensive function,
Here, you filter the A very common solution for this type of situation is rewriting your code to use an explicit
This will only call
You can code some other solutions by using a
The good news is that there’s only one call to Figuring out what’s actually happening in the double list comprehension takes a fair amount of head-scratching. Essentially, the second You can rewrite the list comprehension using the walrus operator as follows:
Note that the parentheses around Let’s look at a slightly more involved and practical example. Say that you want to use the Real Python feed to find the titles of the last episodes of the Real Python Podcast. You can use the Real Python Feed Reader to download information about the latest Real Python publications. In order to find the podcast episode titles, you’ll use the third-party Parse package. Start by installing both into your virtual environment:
You can now read the latest titles published by Real Python: >>>
Podcast titles start with >>>
Compiling the pattern beforehand speeds up later comparisons, especially when you want to match the same pattern over and over. You can check if a string matches your pattern using either >>>
Note that Parse is able to pick
out the podcast episode number and the episode name. The episode number is converted to an integer data type because you used the Let’s get back to the task at hand. In order to list all the recent podcast titles, you need to check whether each string matches your pattern and then parse out the episode title. A first attempt may look something like this: >>>
Though it works, you might notice the same problem you saw earlier. You’re parsing each title twice because you filter out titles that match your pattern and then use that same pattern to pick out the episode title. Like you did earlier, you can avoid the double work by rewriting the list comprehension using either an explicit >>>
Assignment expressions work well to simplify these kinds of list comprehensions. They help you keep your code readable while you avoid doing a potentially expensive operation twice. In this section, you’ve focused on examples where list comprehensions can be rewritten using the walrus operator. The same principles also apply if you see that you need to repeat an operation in a dictionary comprehension, a set comprehension, or a generator expression. The following example uses a generator expression to calculate the average length of episode titles that are over >>>
The generator expression uses an assignment expression to avoid calculating the length of each episode title twice. While LoopsPython has two different loop constructs: In
This works but has an unfortunate
repetition of identical If you want to make your code more maintainable, it’s quite common to rewrite this kind of logic with a
This has the advantage of avoiding the repetition. However, the actual check is now harder to spot. Assignment expressions can often be used to simplify these kinds of loops. In this example, you can now put the check back together with
The You can expand the box below to see the full code of the multiple-choice quiz program and try a couple of questions about the walrus operator yourself. This script runs a multiple-choice quiz. You’ll be asked each of the questions in order, but the order of answers will be shuffled each time:
Note that the first answer is assumed to be the correct one. You can add more questions to the quiz yourself. Feel free to share your questions with the community in the comments section below the tutorial! You can often simplify Witnesses and CounterexamplesIn the examples you’ve seen so far, the In this section, you’ll learn how you can
find witnesses when calling By applying similar logic, you’ll also learn how you can find counterexamples when working with In order to have some data to work with, define the following list of city names: >>>
You can use >>>
In each of these cases,
In other words, you want a witness or a counterexample to justify the answer. Capturing a witness to an >>>
Here, you first capture all city names that start with By using the >>>
You can capture a witness inside the You can see what’s happening more clearly by wrapping >>>
Note that Even when >>>
However, in this case, Walrus Operator SyntaxOne of the main reasons assignments were not expressions in Python from the beginning is that
the visual likeness of the assignment operator ( As you saw at the beginning of this tutorial, you can’t use a plain assignment expression to assign a value: >>>
It’s syntactically legal to use an assignment expression to only assign a value, but only if you add parentheses: >>>
Even though it’s possible, however, this really is a prime example of where you should stay away from the walrus operator and use a traditional assignment statement instead. PEP 572 shows several other examples where the >>>
In all these cases, you’re better served using >>>
None of these examples make your code more readable. You should instead do the extra assignment separately by using a traditional assignment statement. See PEP 572 for more details about the reasoning. There’s one use case where the >>>
The Here, To use assignment expressions inside f-strings, you need to add parentheses: >>>
This updates the value of Let’s look at some other situations where assignment expressions are illegal:
When you’re using the walrus operator, it will behave similarly to traditional assignment statements in many respects:
The general design of assignment expressions is to make them easy to use when they are helpful but to avoid overusing them when they might clutter up your code. Walrus Operator PitfallsThe walrus operator is a new syntax that is only available in Python 3.8 and
later. This means that any code you write that uses the If you need to support older versions of Python, you can’t ship code that uses assignment expressions. There are some projects, like Experience with the walrus operator indicates that There are many times it’s possible for you to use the walrus operator, but where it won’t necessarily improve the readability or efficiency of your code. In those cases, you’re better off writing your code in a more traditional manner. ConclusionYou now know how the new walrus operator works and how you can use it in your own code. By using the In this tutorial, you learned how to:
To learn more about the details of assignment expressions, see PEP 572. You can also check out the PyCon 2019 talk PEP 572: The Walrus Operator, where Dustin Ingram gives an overview of both the walrus operator and the discussion around the new PEP. How do you use the walrus operator in Python?Python 3.8 introduced a new walrus operator := . The name of the operator comes from the fact that is resembles eyes and tusks of a walrus of its side. The walrus operator creates an assignment expression. The operator allows us to assign a value to a variable inside a Python expression.
What is this := in Python?There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.
What does the := operator do?The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable.
How does the walrus operator look in Python?Assignment expression are written with a new notation (:=) . This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side. The assignment expression allows you to assign True to walrus , and immediately print the value.
|