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.
#more
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
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
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*