The Walrus Operator - New in Python 3.8

In this Python Tutorial I show you the new assignment expression also known as the walrus operator. This Python feature is new in Python 3.8. It can be used to evaluate an expression and simultaneously assign it to a variable. This can be useful to simplify the code in some cases. I will show you the syntax of the walrus operator and two useful examples.

The code from this Tutorial can also be found on GitHub.

Assignment expression also known as walrus operator

# := # var := expr

It is a way to evaluate an expression and assign it to a variable in the same statement. Use the walrus operator always in the context of an expression rather than as a stand alone statement.

walrus = False print(walrus) print(walrus := True) print(walrus)

Useful to simplify your code

Without walrus:

inputs = list() while True: current = input("Write something ('quit' to stop): ") if current == "quit": break inputs.append(current) print(inputs)

With walrus:

inputs = list() while (current := input("Write something ('quit' to stop): ")) != "quit": inputs.append(current) print(inputs)

Useful for list comprehension and api requests

E.g. we have to wait for data repeatedly and then want to filter it with list comprehension:

simulate api request:

import random def get_score_data(): return random.randrange(1, 10)

Without walrus:

scores = [get_score_data() for _ in range(20)] scores = [score for score in scores if score >= 5] print(scores)

With walrus:

scores = [score for _ in range(20) if (score := get_score_data()) >= 5] print(scores)

FREE VS Code / PyCharm Extensions I Use

🪁 Code faster with Kite, AI-powered autocomplete: Link *

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* These are affiliate links. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses