Python 3.8 new feature: the Walrus operator

You can find the new features (post) here: https://www.codementor.io/ruturajkiranvaidya/introduction-to-python-3-8-new-feature-the-walrus-operator-vcv2d3zxw?utm_swu=7179

The walrus operator :=

This operator, the Walrus operator, let you assigns the value of a variable to another to use it as part of an expression.

sample_data = [
    {"userId": 1, "id": 1, "title": "delectus aut autem", "completed": False},
    {"userId": 1, "id": 2, "title": "quis ut nam facilis", "completed": False},
    {"userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": False},
    {"userId": 1, "id": 4, "title": "et porro tempora", "completed": True},
    {"userId": 1, "id": 4, "title": None, "completed": True},
]

print("With Python 3.8 Walrus Operator:") 
for entry in sample_data: 
    if title := entry.get("title"):
        print(f'Found title: "{title}"')

print("Without Walrus operator:")
for entry in sample_data:
    title = entry.get("title")
    if title:
        print(f'Found title: "{title}"')

Example from (https://medium.com/hultner/try-out-walrus-operator-in-python-3-8-d030ce0ce601).

ith Python 3.8 Walrus Operator:
Found title: "delectus aut autem"
Found title: "quis ut nam facilis"
Found title: "fugiat veniam minus"
Found title: "et porro tempora"
Without Walrus operator:
Found title: "delectus aut autem"
Found title: "quis ut nam facilis"
Found title: "fugiat veniam minus"
Found title: "et porro tempora"

Other example

import re

with open("sample.txt") as file:
    for line in file:
        if text := re.findall("f",line):
            print(line.strip())
            print(text)

print("\n--------- without := -------------\n")

with open("sample.txt") as file:
    for line in file:
        text = re.findall("f",line)
        if (text):
            print(line.strip())
            print(text)

 

fafsdfg
['f', 'f', 'f']
sdfgs
['f']
fdg
['f']
hsfhfghfs
['f', 'f', 'f']

--------- without := -------------

fafsdfg
['f', 'f', 'f']
sdfgs
['f']
fdg
['f']
hsfhfghfs
['f', 'f', 'f']

 

Other … examples

# instead of

x = [f(x), f(x)**2, f(x)**3]

# you can do

x = [y := f(x), y**2, y**3]

# for more efficiency
lines = [1,2,3]

def f(x):
    if x > 1:
        return x

d = []
for l in lines:
    if f(l):
        d.append(l)

# you can do so
d = [y for l in lines if (y := f(l))]

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.