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
inputs = list() while True: current = input("Write something ('quit' to stop): ") if current == "quit": break inputs.append(current) print(inputs)
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)
scores = [get_score_data() for _ in range(20)] scores = [score for score in scores if score >= 5] print(scores)
scores = [score for _ in range(20) if (score := get_score_data()) >= 5] print(scores)