Introduction

Python 3.8, released in October 2019, adds assignment expressions to Python via the := syntax. The assignment expression syntax is also sometimes called “the walrus operator” because := vaguely resembles a walrus with tusks.

Assignment expressions allow variable assignments to occur inside of larger expressions. While assignment expressions are never strictly necessary to write correct Python code, they can help make existing Python code more concise. For example, assignment expressions using the := syntax allow variables to be assigned inside of if statements, which can often produce shorter and more compact sections of Python code by eliminating variable assignments in lines preceding or following the if statement.

In this tutorial, you will use assignment expressions in several examples to produce concise sections of code.

Prerequisites

To get the most out of this tutorial, you will need:

  • Python 3.8 or above. Assignment expressions are a new feature added starting in Python 3.8. You can view the  How To Install Python 3 and Set Up a Programming Environment on an Ubuntu 18.04 Server tutorial for help installing and upgrading Python.
  • The Python Interactive Console. If you would like to try out the example code in this tutorial you can use the  How To Work with the Python Interactive Console tutorial.
  • Some familiarity with while loops, if statements, list comprehensions, and functions in Python 3 is useful, but not necessary. You can review our  How To Code in Python 3 tutorial series for background knowledge.

#python #programming

How to Use Assignment Expressions in Python
11.00 GEEK