tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Modern Python > Type Hints and Dataclasses > Python Walrus Operator :=

Python Walrus Operator :=

Author: Venkata Sudhakar

The walrus operator := (introduced in Python 3.8) lets you assign a value to a variable and use that value in the same expression. Its name comes from its resemblance to a walrus face. Before := you often had to compute a value, assign it to a variable, then use it on the next line. With := you can do both in one step, which is especially useful inside while loops and if conditions where you want to test a value and also keep it.

The most common use case is a while loop that reads data until it runs out. Without :=, you have to either duplicate the read call or use a break pattern. With := you write while chunk := file.read(8192): which reads, assigns, and tests in one expression - the loop stops as soon as read() returns an empty value. The operator is also useful inside list comprehensions to avoid calling an expensive function twice: once to filter and once to use the result.

The below example shows the walrus operator in three practical situations: reading file chunks, processing database batches, and filtering with an expensive check inside a list comprehension.


It gives the following output,

Got: line one
Got: line two
Got: line three
Done - readline returned empty string

It gives the following output,

Processing batch: [0, 1, 2]
Processing batch: [3, 4, 5]
Processing batch: [6, 7, 8]
Processing batch: [9]
Done. Total rows processed: 10

Valid: MIG-001 -> num=1
Valid: MIG-042 -> num=42
Valid: MIG-100 -> num=100

When to use := and when not to:

Use := when you need a value both to test it (in a condition) and to use it (in the loop body or expression). The main cases are: while loops reading data until exhausted, if conditions where you want to keep the matched value, and list/dict comprehensions where filtering and transforming uses the same computed result. Avoid := when a regular assignment on its own line is just as clear - the operator helps readability only when it removes a genuine awkwardness, not as a way to write unnecessarily compact code.


 
  


  
bl  br