Member-only story

The walrus operator

Elshad Karimov
2 min readApr 21, 2024
Photo by Clément Hélardot on Unsplash

The walrus operator, introduced in Python 3.8, is denoted by :=. Officially known as the assignment expression, it allows you to assign values to variables as part of an expression without having to do it in a separate line. This can simplify some patterns of code, particularly those involving loops or conditions, by reducing the amount of code needed.

Key Features of the Walrus Operator

  1. Efficiency in Code: It helps streamline expressions where you might otherwise need multiple lines to perform an assignment followed by a condition or other operation.
  2. Readability and Conciseness: Although it condenses code, whether it improves readability can depend on the context and the user’s familiarity with this feature.

Example 1: Using the Walrus Operator in a Loop

A common use case is reading lines from a file or input until an end condition is met. Here’s how you might use the walrus operator in a loop to read from standard input until a blank line is entered:

# Example of using the walrus operator to read input until a blank line is entered
print("Enter text (leave blank to stop):")
while (line := input()) != '':
print(f'You entered: {line}')

In this example:

  • The input() function…

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet