Professional Documents
Culture Documents
Python walrus operator tutorial shows how to use walrus operator in Python.
Python 3.8 introduced a new walrus operator :=. The name of the operator comes from the fact
that is resembles eyes and tusks of a walrus of its side.
The walrus operator creates an assignment expression. The operator allows us to assign a value to
a variable inside a Python expression. It is a convenient operator which makes our code more
compact.
print(is_new := True)
is_new = True
print(is_new)
read_words.py
#!/usr/bin/env python
words = []
print(words)
$ ./read_words.py
Enter word: cloud
Enter word: falcon
Enter word: rock
Enter word: quit
['cloud', 'falcon', 'rock']
test_length.py
#!/usr/bin/env python
In the example, we use the walrus operator to test the length of a word. If a word has less than
three characters, a warning is issued. We determine and assign the length of a word in one shot.
$ ./test_length.py
warning, the word ab has 2 characters
warning, the word a has 1 characters
words.txt
falcon
sky
cloud
water
rock
forest
read_file.py
#!/usr/bin/env python
print(line.rstrip())
The example reads the file using the readline() method. The walrus operator makes the code
shorter.
traversing.py
#!/usr/bin/env python
users = [
{'name': 'John Doe', 'occupation': 'gardener'},
{'name': None, 'occupation': 'teacher'},
{'name': 'Robert Brown', 'occupation': 'driver'},
{'name': None, 'occupation': 'driver'},
{'name': 'Marta Newt', 'occupation': 'journalist'}
]
In the example, we have None values in the dictionaries. We print all users who have name
specified.
Google Ads -
Sitio O cial
Con Google Ads, no hay
contratos ni mínimo de
Google Ads inversión.
$ ./traversing.py
John Doe is a gardener
Robert Brown is a driver
Marta Newt is a journalist
search.py
#!/usr/bin/env python
import re
pattern = re.compile(r'book')
if match := pattern.search(data):
print(f'The word {pattern.pattern} is at {match.start(), match.end()}')
else:
print(f'No {pattern.pattern} found')
We search for a pattern and assign the match (if found) to a variable in one go.
$ ./search.py
The word book is at (11, 15)