0
0
PythonConceptBeginner · 3 min read

Walrus Operator in Python: What It Is and How to Use It

The walrus operator (:=) in Python allows you to assign a value to a variable as part of an expression. It helps write shorter and clearer code by combining assignment and evaluation in one step.
⚙️

How It Works

The walrus operator := lets you assign a value to a variable while using that value immediately in an expression. Think of it like grabbing a snack and eating it right away instead of putting it down first and then eating it later. This saves you from repeating the same calculation or function call.

Normally, you assign a value on one line and then use it on the next. With the walrus operator, you do both at once. This is especially useful in loops or conditions where you want to check a value and keep it for later without writing extra lines.

💻

Example

This example shows how the walrus operator assigns and uses a value inside a while loop to read input until an empty string is entered.

python
while (line := input('Enter text (empty to stop): ')) != '':
    print(f'You entered: {line}')
Output
Enter text (empty to stop): hello You entered: hello Enter text (empty to stop): world You entered: world Enter text (empty to stop):
🎯

When to Use

Use the walrus operator when you want to both assign and use a value in one step, making your code shorter and easier to read. It is great for loops, conditions, and comprehensions where you would otherwise call a function or expression twice.

For example, reading input until a condition is met, processing data while checking its value, or filtering items in a list comprehension can all benefit from the walrus operator.

Key Points

  • The walrus operator := assigns and returns a value in one expression.
  • It helps avoid repeating expensive or complex calculations.
  • Introduced in Python 3.8, so it requires that version or newer.
  • Improves code readability by reducing lines and nesting.

Key Takeaways

The walrus operator (:=) assigns and returns a value in a single expression.
It reduces code repetition by combining assignment and use.
Ideal for loops, conditions, and comprehensions to simplify code.
Requires Python 3.8 or later to use.
Improves readability by making code shorter and clearer.