Skip to main content
  1. Posts/

The Walrus Operator

··153 words·1 min·

The walrus operator (:=), introduced in Python 3.8, allows you to assign values to variables as part of an expression. This is useful when you want to compute and check a value without repeating the computation in multiple places.

data = [1, 2, 3, 4, 5]

if (avg := sum(data) / len(data)) > 3:
    print(f"Average is {avg}")

Here, avg is assigned and checked at the same time. This removes the need for an extra line and makes your code easier to read.

More information at the link 👇

Also published on LinkedIn.
Juan Pedro Bretti Mandarano
Author
Juan Pedro Bretti Mandarano