FLOSS Project Planets

Real Python: The Walrus Operator: Python 3.8 Assignment Expressions

Planet Python - Mon, 2021-08-09 10:00

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 := operator gives you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator.

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:

  • Identify the walrus operator and understand its meaning
  • Understand use cases for the walrus operator
  • Avoid repetitive code by using the walrus operator
  • Convert between code using the walrus operator and code using other assignment methods
  • Understand the impacts on backward compatibility when using the walrus operator
  • Use appropriate style in your assignment expressions

Note that all walrus operator examples in this tutorial require Python 3.8 or later to work.

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.

Walrus Operator Fundamentals

Let’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 := operator is officially known as the assignment expression operator. During early discussions, it was dubbed the walrus operator because the := syntax resembles the eyes and tusks of a sideways walrus. You may also see the := operator referred to as the colon equals operator. Yet another term used for assignment expressions is named expressions.

Hello, Walrus!

To get a first impression of what assignment expressions are all about, start your REPL and play around with the following code:

>>> 1>>> walrus = False 2>>> walrus 3False 4 5>>> (walrus := True) 6True 7>>> walrus 8True

Line 1 shows a traditional assignment statement where the value False is assigned to walrus. Next, on line 5, you use an assignment expression to assign the value True to walrus. After both lines 1 and 5, you can refer to the assigned values by using the variable name walrus.

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.

Note: A statement in Python is a unit of code. An expression is a special statement that can be evaluated to some value.

For example, 1 + 2 is an expression that evaluates to the value 3, while number = 1 + 2 is an assignment statement that doesn’t evaluate to a value. Although running the statement number = 1 + 2 doesn’t evaluate to 3, it does assign the value 3 to number.

In Python, you often see simple statements like return statements and import statements, as well as compound statements like if statements and function definitions. These are all statements, not expressions.

There’s a subtle—but important—difference between the two types of assignments seen earlier with the walrus variable. An assignment expression returns the value, while a traditional assignment doesn’t. You can see this in action when the REPL doesn’t print any value after walrus = False on line 1, while it prints out True after the assignment expression on line 5.

You can see another important aspect about walrus operators in this example. Though it might look new, the := operator does not do anything that isn’t possible without it. It only makes certain constructs more convenient and can sometimes communicate the intent of your code more clearly.

Note: You need at least Python 3.8 to try out the examples in this tutorial. If you don’t already have Python 3.8 installed and you have Docker available, a quick way to start working with Python 3.8 is to run one of the official Docker images:

$ docker container run -it --rm python:3.8-slim

This will download and run the latest stable version of Python 3.8. For more information, see Run Python Versions in Docker: How to Try the Latest Python Release.

Now you have a basic idea of what the := operator is and what it can do. It’s an operator used in assignment expressions, which can return the value being assigned, unlike traditional assignment statements. To get deeper and really learn about the walrus operator, continue reading to see where you should and shouldn’t use it.


Like 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 := operator can be used to improve your code.

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.


In 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:

Read the full article at https://realpython.com/python-walrus-operator/ »

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Categories: FLOSS Project Planets

Python for Beginners: Variables and Constants in Python

Planet Python - Mon, 2021-08-09 08:18

While studying about programming in python, you must have encountered certain phrases like keywords, variables, constants and literals. In this article, we will learn about variables and constants and we will study the underlying concepts for their definition and usage in python.

What are variables in Python?

A variable in python is a name which is used to refer to an object in the memory. Variables are also termed as references because they refer to a specific object in the memory.

For example, the variable myNum given in the following code snippet will refer to an object of type integer which contains 1117 as its value.

myNum = 1117

We can assign a value to a variable. Likewise, we can also assign a variable to a variable as follows.

myNum=1117 anotherNum=myNum

When we assign a variable to a variable, both the variables start pointing to the same object in the memory. This can be verified using the id() method which gives an unique identifier for every object.

myNum = 1117 anotherNum = myNum print("id of myNum is:", id(myNum)) print("id of anotherNum is:", id(anotherNum))


id of myNum is: 140209154920336 id of anotherNum is: 140209154920336

In the above example, we can see that id of both the variables is same which confirms that both the variables refer to the same object.

We can also modify values in the variables. While modifying values for mutable data types, the new value is assigned to the same object. For example, If we modify the value for a key in the python dictionary given in the following example, the dictionary will remain the same. This can be verified from the id of the dictionary before and after the modification.

myDict = {1: 2} print("Id of myDict before modification:", id(myDict)) myDict[1] = 4 print("Id of myDict after modification:", id(myDict))


Id of myDict before modification: 140457374471040 Id of myDict after modification: 140457374471040

When we modify values assigned to immutable data types like integers, a new object is created and assigned to the variable. This can be seen in the following example.

myNum=1117 print("Id of myNum before modification:", id(myNum)) myNum = 1118 print("Id of myNum after modification:", id(myNum))


Id of myNum before modification: 140485377224528 Id of myNum after modification: 140485378289104

In the above example, we can see that the id of the myNum variable has changed. This confirms that a new object has been created during assignment of new value to myNum.

Conventions for defining Variables in Python

A variable name in python always starts with an alphabet. We can start a variable with capital or small case letters but it should never start with a number or any special character.

name="PythonForBeginners" #correct variable name Name="PythonForBeginners" #correct variable name 2name="PythonForBeginners" #incorrect variable name #name="PythonForBeginners" #incorrect variable name

A variable can have underscore _ character but it should never have any other special character like #,@,$,%,&,!.

my_name="PythonForBeginners" #correct variable name my&name="PythonForBeginners" #incorrect variable name

When a variable name consists of multiple words, we can use camelCase naming convention. In camelCase convention, we start a variable with a small letter and each word in the variable is started using capital letters as follows.

myName="PythonForBeginners" #correct variable name

We can also use underscore to separate different words in a variable name as follows.

my_name="PythonForBeginners" #correct variable name

Python is a case sensitive language. It means that variable names having the same spelling but different cases will refer to different objects.

myNum=1117 MyNum = 1118 print("myNum is:",myNum) print("MyNum is:",MyNum)


myNum is: 1117 MyNum is: 1118

Keywords should not be used as variable names in python, otherwise error occurs during execution of the program.

in =1117 #incorrect variable name What are constants in Python?

Constants are literals which contain a value which is not supposed to be changed during the execution of the program.

In python, variables and constants are not differentiated from each other by the interpreter. In a program, we differentiate a variable from a constant by using the naming conventions.

A constant in python is defined using only uppercase letters and underscores. Generally, constants are defined in a module and then they are imported into a program whenever we need to use them. For example, we can use the constant PI from the cmath module after importing it as follows.

import cmath print("Value of PI is:",cmath.pi)


Value of PI is: 3.141592653589793

We can also modify a constant after importing it as follows.

import cmath print("Value of PI is:", cmath.pi) cmath.pi = 1117 print("modified value of PI is:", cmath.pi)


Value of PI is: 3.141592653589793 modified value of PI is: 1117

Being able to modify the value in a constant entirely violates the idea behind constants. To avoid this, there should be getter functions defined in the modules to access the constants. This will restrict the user to modify the values.


In this article, we have studied variables and constants in python. We have also seen the conventions for naming the variables and constants in python.We can also write the programs used in this article with exception handling using python try except to make the programs more robust and handle errors in a systematic way . Stay tuned for more informative articles.

The post Variables and Constants in Python appeared first on PythonForBeginners.com.

Categories: FLOSS Project Planets