Python's Walrus Operator

Python's Walrus Operator

What is the Walrus Operator?

Python 3.8 introduces the creatively named "walrus" operator. Expressed via :=, the walrus operator allows you to assign values to a variable as part of an expression. The key benefit to this new operator is that it reduces the amount of written code required.

Previously if we wanted to assign a variable and print its value, you would have done something like this:

>>> device_type = "router"
>>> print(device_type)
router

In Python 3.8, you’re allowed to combine these two statements into one, using the walrus operator:

>>> print(device_type := "router")
router

Example

Let us build the context of our example out some more. Let’s say we have a simple dict() containing some device data, like so:

device_data = [ 
    {"device_type": "router",  "name": "rtr001"},
    {"device_type": "switch", "name": "sw001"},
    {"device_type": "firewall",  "name": "fw001"}
] 

The code typically required would look something like the below:

# Without Walrus Operator 
for device in device_data: 
    name = device.get("name") 
    if name: 
        print(f'Found name: "{name}"') 

If we now use the walrus operator, we can collapse our if condition and the name assignment into a single line like so:

# With Walrus Operator...
for device in device_data:  
    if name := device.get("name"): 
        print(f'Found name: "{name}"') 

Subscribe to our newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!