2 minutes
Assignment Expressions (The Walrus Operator)
Welcome to part seven of our Python 3 features series! Today, we’ll wrap things up by looking at the walrus operator (:=
) and positional-only parameters , two syntax twists introduced in Python 3.8.
Assignment Expressions
Ever wish you could assign a value to a variable right inside an expression? That’s exactly what the walrus operator lets you do:
# Without walrus:
line = input('> ')
while line:
print(line)
line = input('> ')
# With walrus:
while (line := input('> ')):
print(line)
You can use it in comprehensions too:
# Without walrus, you'd have to call f(x) twice
results = [f(x) for x in data if f(x) > 10]
# With walrus, call once and reuse:
results = [y for x in data if (y := f(x)) > 10]
Just be careful , overusing it can make code harder to read. But for simple loops and filters, it’s a neat time-saver.
Positional-Only Parameters
Sometimes you want to force callers to pass arguments by position, not by name. Enter the /
marker in function definitions:
# `x` and `y` are positional-only; `z` can be positional or keyword
def func(x, y, /, z):
print(x, y, z)
func(1, 2, 3) # works
func(1, 2, z=3) # works
func(x=1, y=2, z=3) # ❌ TypeError: x and y are positional-only
This is handy for APIs where you don’t want certain parameters to be tied to a name, or where the parameter name might change later.
Common Example: pow
Built-in pow
takes three positional-only args:
pow(2, 3) # 8
pow(2, 3, 5) # pow(2,3) % 5 = 3
# pow(base=2, exp=3) # ❌ TypeError
Using the /
marker makes your own functions behave like this.
That’s it for the series! We’ve covered everything from data structures and coroutines to syntax sugar and the latest Python twists. Hope you picked up some new tricks , happy coding!