Python Walrus Operator: The Assignment Expression

Python Walrus Operator, written as :=, is a relatively new feature added in Python 3.8. A special operator lets you assign a value to a variable while using that value in a larger expression, all in a single line of code. Think of it as a shortcut for assigning and using a value simultaneously. While it can shorten your code, it is important to use Python Walrus Operator wisely so your code remains easy to understand. It is also called an assignment operator.
Table of Contents

What Is Python Walrus Operator?

Python Walrus Operator is a new type of operator introduced in Python 3.8. It’s written as := and is formally known as an “assignment expression.” The operator gets its nickname from its resemblance to the eyes and tusks of a walrus. Python Walrus Operator allows you to assign a value to a variable within an expression. This means you can both assign a value and use that value in the same line of code. Before this operator, you would typically need separate lines to assign a value and then use it in a condition or calculation. It simplifies your code and makes it more readable in certain situations.

Python Walrus Operator Syntax

(variable := expression)

Explanation

  • :=: This is Walrus Operator.
  • variable: Variable name you want to assign a value to.
  • expression: Any valid Python expression that produces a value.
  • (): The parentheses are often necessary to clearly define the scope of the assignment expression. For example, you might write if (x := 10) > 5:, which assigns 10 to x and then checks if x is greater than 5.

Example of Python Walrus Operator

n = 15
if (n := n - 5) > 5:
    print(f"The value is {n} which is greater than 5")

Explanation

  • n = 15: Initialize a variable n with the value 15.
  • if (n := n - 5) > 5:: Line uses the Python Walrus Operator.
    • n := n - 5 assigns the result of n - 5 (which is 10) back to n.
    • Entire expression (n := n - 5) also evaluates to 10 because the value assigned is also returned by the operator.
    • Then, > 5 checks if the result (10) is greater than 5.
  • print(f"The value is {n} which is greater than 5"): Since 10 is greater than 5, this line is executed, printing the message along with the new value of n (which is 10).

Output

The value is 10 which is greater than 5


How and When Python Walrus Operator is Helpful

Python Walrus Operator can be helpful in situations where you need to use a value multiple times within an expression or a block of code, but you only want to calculate it once. Instead of calculating the value in advance and storing it in a separate variable or calculating it repeatedly, the Walrus Operator lets you do both the calculation and the assignment in a single step. This improves code readability by keeping related logic closer together. It’s especially useful when the calculation is part of a condition (like in an if or while statement) or when working with comprehensions or generator expressions.

Example

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

# Without Walrus
length = len(data)
if length > 3:
    print(f"List is long, it has {length} elements")

# With Walrus
if (length := len(data)) > 3:
    print(f"List is long, it has {length} elements")

Explanation

  • data = [1, 2, 3, 4, 5]: We create a sample list called data.
  • # Without Walrus: This is a comment indicating the following code does not use the Walrus Operator.
  • length = len(data): We calculate the length of the list and store it in length.
  • if length > 3:: We check if length is greater than 3.
  • print(f"List is long, it has {length} elements"): If the condition is true, we print a message.
  • # With Walrus: This is a comment indicating the following code does use the Walrus Operator.
  • if (length := len(data)) > 3:: We use the Walrus Operator := to assign the length of data to length within the if condition.
  • print(f"List is long, it has {length} elements"): If the condition is true, we print the same message. The code with the Walrus operator achieves the same result in fewer lines.

Output

List is long, it has 5 elements
List is long, it has 5 elements


Lists and Dictionaries with Python Walrus Operator

When working with lists and dictionaries, the Walrus Operator can streamline code where you need to check for the existence of an element or a key and then use it. Its main advantage is to make your code more concise, especially when you want to check if a key is in a dictionary and perform some operation with its value.

Syntax

# Dictionaries
if (value := my_dict.get(key)) is not None:
    # Do something with value

# Lists
if (item := my_list[index]) some_condition:
    # Do something with item

Explanation

  • if (value := my_dict.get(key)) is not None:: For dictionaries, the Python Walrus Operator := assigns the result of my_dict.get(key) to value. We then check if value is not None (meaning the key exists).
  • if (item := my_list[index]) some_condition:: For lists, we use the Walrus Operator to assign the element at my_list[index] to item. We then evaluate some condition using that item.

Example

my_dict = {"a": 1, "b": 2, "c": 3}

if (value := my_dict.get("b")) is not None:
    print(f"Value for key 'b' is: {value}")

my_list = [10, 20, 30]

if (item := my_list[1]) > 15:
    print(f"Item at index 1 is: {item}")

Explanation

  • my_dict = {"a": 1, "b": 2, "c": 3}: Creates a dictionary.
  • if (value := my_dict.get("b")) is not None:: Uses the Python Walrus Operator to assign the value associated with key “b” to value. It then checks if value is not None.
  • print(f"Value for key 'b' is: {value}"): Prints the value if the key exists.
  • my_list = [10, 20, 30]: Creates a list.
  • if (item := my_list[1]) > 15:: Uses the Walrus Operator to assign the element at index 1 to item. It then checks if item is greater than 15.
  • print(f"Item at index 1 is: {item}"): Prints the item if the condition is true.

Output

Value for key ‘b’ is: 2
Item at index 1 is: 20


List Comprehensions with Python Walrus Operator

Python Walrus Operator can be used within list comprehensions to assign values to variables that you can then use in the comprehension’s expression or condition. This is helpful when you need to perform a calculation once and reuse the result within the comprehension, avoiding redundant computations.

Syntax

[expression for item in iterable if (variable := some_calculation(item)) condition]

Explanation

  • [expression ... ]: This is the basic structure of a list comprehension.
  • for item in iterable: This iterates over the iterable.
  • if (variable := some_calculation(item)): The Python Walrus Operator := assigns the result of some_calculation(item) to variable.
  • condition: The condition can then use the variable.
  • expression: The expression at the beginning can also use the variable.

Example

numbers = [1, 2, 3, 4, 5]
filtered_numbers = [
    y for x in numbers
    if (y := x * 2) > 6
]
print(filtered_numbers)

Explanation

  • numbers = [1, 2, 3, 4, 5]: Creates a list of numbers.
  • filtered_numbers = [ ... ]: Initializes a list comprehension to create a new list called filtered_numbers.
  • y for x in numbers: Iterates through the numbers list, assigning each element to x.
  • if (y := x * 2) > 6:
    • The Python Walrus Operator := assigns the value of x * 2 to y.
    • Then, it checks if y is greater than 6.
  • If the condition is true, y (which is x * 2) is added to the filtered_numbers list.
  • print(filtered_numbers): Prints the new list, which contains only the doubled values greater than 6: [8, 10].

Output

[8, 10]


While Loops with Python Walrus Operator

Python Walrus Operator can be particularly useful in while loops where you need to repeatedly check a condition based on a value that’s updated within the loop. Instead of assigning the value in a separate line before the loop or at the end of the loop body, you can use the Walrus Operator to do the assignment directly within the while condition.

Syntax

while (variable := some_function()) condition:
      # Do something with variable
      # …

Explanation of the Syntax:

  • while (variable := some_function()) condition:: The Python Walrus Operator := assigns the result of some_function() to variable within the while loop’s condition.
  • The condition is then evaluated using the newly assigned value of variable.
  • The loop continues as long as the condition is true.

Example

# Simulate reading lines from a file, stopping when an empty line is encountered
def get_next_line():
  """Simulates reading a line from a file."""
  lines = ["line 1", "line 2", "", "line 4"]
  for line in lines:
      yield line
my_line = get_next_line()

while (line := next(my_line, '')) != '':
    print(f"Processing: {line}")

Explanation

  • def get_next_line():: Defines a generator function to simulate reading lines from a file.
  • lines = ["line 1", "line 2", "", "line 4"]: A list of strings to simulate lines in a file.
  • for line in lines:: Iterates through the lines.
  • yield line: Yields each line one at a time, making this a generator.
  • my_line = get_next_line(): It calls the generator function get_next_line(). It will return a generator object.
  • while (line := next(my_line, '')) != ''::
    • The Python Walrus Operator := assigns the next value from my_line (which yields lines from generator function get_next_line) to line. If there are no more values, it assigns an empty string ” (provided as the default value to next).
    • The loop continues as long as line is not an empty string.
  • print(f"Processing: {line}"): Prints the current line. The loop will process “line 1”, “line 2”, and then stop because the next line is an empty string which makes the while loop condition false.

Output

Processing: line 1
Processing: line 2


Conclusion

Python Walrus Operator ( := ) allows you to perform assignments within expressions, reducing the need for extra lines of code and improving readability in certain situations. However, it’s important to be mindful of pitfalls like reduced clarity when overused and understand its precedence and scoping rules. If you are a beginner programmer, do not overuse it. If you master it over time, you will know where to use it to make code more efficient.


Python Reference

Assignment expressions

Table of Contents