DEV Community

Cover image for Python by Structure: The Walrus Operator - Assignment Where You Need It
Aaron Rose
Aaron Rose

Posted on

Python by Structure: The Walrus Operator - Assignment Where You Need It

Timothy squinted at a code review comment on his screen. "Margaret, someone left a note saying I should use the 'walrus operator' here. I looked it up and found := but... I don't understand when I'm supposed to use it. It just looks like a typo to me."

Margaret came over and examined his code:

def process_file(filename):
    with open(filename, 'r') as file:
        line = file.readline()
        while line:
            if len(line) > 80:
                print(f"Long line: {line[:80]}...")
            line = file.readline()
Enter fullscreen mode Exit fullscreen mode

"Ah, see the repetition?" Margaret pointed at the two line = file.readline() statements. "You're reading a line before the loop, then reading again at the end of each iteration. The walrus operator lets you assign and use a value in the same expression."

"But... where would I put it?" Timothy asked.

The Problem: Assignment Outside the Expression

"Let me show you," Margaret said, rewriting the function:

def process_file(filename):
    with open(filename, 'r') as file:
        while (line := file.readline()):
            if len(line) > 80:
                print(f"Long line: {line[:80]}...")
Enter fullscreen mode Exit fullscreen mode

"Wait," Timothy blinked. "The assignment is... inside the while condition?"

"Exactly. Let me show you the structure."

Tree View:

process_file(filename)
    With open(filename, 'r') as file
        While (line := file.readline())
            If len(line) > 80
            └── print(f'Long line: {line[:80]}...')
Enter fullscreen mode Exit fullscreen mode

English View:

Function process_file(filename):
  With open(filename, 'r') as file:
    While (line := file.readline()):
      If len(line) > 80:
        Evaluate print(f'Long line: {line[:80]}...').
Enter fullscreen mode Exit fullscreen mode

Timothy studied the structure. "So line := file.readline() assigns the value to line AND returns it for the while condition to check?"

"Precisely," Margaret confirmed. "The walrus operator := is an assignment expression - it assigns a value and evaluates to that value. That's why you can use it inside conditions, comprehensions, anywhere an expression is valid."

"But I thought you couldn't do assignment inside expressions?" Timothy asked.

"You couldn't with the regular = operator," Margaret said. "That's statement-level assignment. The walrus operator := is expression-level assignment. Python 3.8 added it specifically for cases like this."

Understanding the Pattern

Margaret pulled up another example where the walrus operator shines:

def analyze_data():
    numbers = [1, 2, 3, 4, 5]
    squared = [y for x in numbers if (y := x * 2) > 4]
    return squared
Enter fullscreen mode Exit fullscreen mode

Tree View:

analyze_data()
    numbers = [1, 2, 3, 4, 5]
    squared =
        Comprehension: y
            For x in numbers
                If (y := (x * 2)) > 4
    Return squared
Enter fullscreen mode Exit fullscreen mode

English View:

Function analyze_data():
  Set numbers to [1, 2, 3, 4, 5].
  Set squared to:
    List comprehension: y
      For each x in numbers
        If (y := (x * 2)) > 4
  Return squared.
Enter fullscreen mode Exit fullscreen mode

"Look at the structure," Margaret said. "The assignment y := x * 2 happens inside the comprehension's filter condition. Without the walrus operator, you'd have to compute x * 2 twice - once to check if it's greater than 4, and again to include it in the result."

Timothy traced the flow. "So I'm assigning y the value of x * 2, then immediately using that y value both in the comparison and as the result?"

"Exactly. The structure makes it clear - the assignment happens right where you need the value."

She showed him what the code would look like without the walrus operator:

def analyze_data_verbose():
    numbers = [1, 2, 3, 4, 5]
    squared = []
    for x in numbers:
        temp = x * 2
        if temp > 4:
            squared.append(temp)
    return squared
Enter fullscreen mode Exit fullscreen mode

Tree View:

analyze_data_verbose()
    numbers = [1, 2, 3, 4, 5]
    squared = []
    For x in numbers
        temp = x * 2
        If temp > 4
        └── squared.append(temp)
    Return squared
Enter fullscreen mode Exit fullscreen mode

English View:

Function analyze_data_verbose():
  Set numbers to [1, 2, 3, 4, 5].
  Set squared to [].
  For each x in numbers:
    Set temp to x * 2.
    If temp > 4:
      Evaluate squared.append(temp).
  Return squared.
Enter fullscreen mode Exit fullscreen mode

"See the difference?" Margaret pointed at the two structures side by side. "The verbose version has a temporary variable and a separate loop. The walrus version does it all in the comprehension."

Where You Can Use It

Timothy nodded slowly. "So the walrus operator is useful when you want to use a computed value multiple times in the same expression?"

"That's one use case," Margaret said. "It's also great in if statements when you want to capture and test a value:"

def process_data(filename):
    if (data := read_file(filename)) is not None:
        return analyze(data)
    return None
Enter fullscreen mode Exit fullscreen mode

Tree View:

process_data(filename)
    If (data := read_file(filename)) is not None
    └── Return analyze(data)
    Return None
Enter fullscreen mode Exit fullscreen mode

English View:

Function process_data(filename):
  If (data := read_file(filename)) is not None:
    Return analyze(data).
  Return None.
Enter fullscreen mode Exit fullscreen mode

"Without the walrus operator, you'd either call read_file() twice or add an extra line to store it first," Margaret explained. "The structure shows the assignment happens right in the condition check."

Timothy looked at his original while loop. "So in my file reading code, I was doing the assignment outside the loop and then again at the end. The walrus operator lets me do it right in the while condition."

"Exactly. The assignment happens where you need it - inside the expression."

"Does it work everywhere?" Timothy asked.

"Almost. You can use it in any expression context - if conditions, while conditions, comprehensions, function arguments. But you can't use it at the statement level. x := 5 by itself would be a syntax error. It has to be part of a larger expression."

Timothy refactored his file reading function, then sat back. "The := doesn't look like a typo anymore. It looks like I'm putting the assignment exactly where I need it in the structure."

"Now you understand why they call it the walrus operator," Margaret smiled. "The := looks like a walrus lying on its side. And just like a walrus, it's distinctive and purposeful."


Explore Python structure yourself: Download the Python Structure Viewer - a free tool that shows code structure in tree and plain English views. Works offline, no installation required.

Python Structure Viewer


Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.

Top comments (0)