Walrus Operator (`:=`): Assignment in Expressions

Published:
• Last updated:
• By Jeferson Peter
Python

why use the walrus operator

  • Avoids repeating function calls or expressions
  • Makes some loops shorter and easier to read
  • Useful for conditions with assignment

example without walrus

data = input("Enter something: ")
while data != "quit":
    print(f"You typed: {data}")
    data = input("Enter something: ")

example with walrus

while (data := input("Enter something: ")) != "quit":
    print(f"You typed: {data}")

šŸ‘‰ Here, the assignment happens inside the while condition.

another example

numbers = [1, 2, 3, 4, 5]
if (length := len(numbers)) > 3:
    print(f"List has {length} elements")
# List has 5 elements

conclusion

The walrus operator is handy when it improves clarity and removes duplication. But avoid overusing it in complex expressions, as it may harm readability.