Tips and Tricks - Difference Between Walrus-Operator and for-Loop

Since Python 3.8, named expressions, also known as the walrus-operator :=, exist. This tip includes a simple use case, where a named expression can be useful and why a for-loop does not work.

Suppose you have a simple text file called data.txt with the following content.

This is just a sample text containing a bunch of words, letters,
you name it. It has absolutely no meaning, so do not spend too much
time adding any meaning to it.

Here, line breaks were only inserted for readability purposes. In the use case, the file consists of a single line. The idea is to print at most ten characters per line until the end of the file is reached. Utilising a named expression, this is fairly easy:

# t.py
f = open("data.txt")

while letters := f.read(10):
    print(letters)

f.close()

Executing it results in ...

$ python t.py
This is ju
st a sampl
e text con
taining a
bunch of w
ord, lette
rs, you na
me it. It
has absolu
tely no me
aning, so
do not spe
nd too muc
h time add
ing any me
aning to i
t.

One may have the idea to replace it with a for-loop as follows:

# t.py
f = open("data.txt")

for letters in f.read(10):
    print(letters)

f.close()

However, we end up with the following result:

$ python t.py
T
h
i
s

i
s

j
u

What happened here? When using a for-loop, the expression after the keyword in is evaluated only once: When the loop is initialised. Consequently, we iterate over a string of ten characters and print each of them on a separate line as shown in the previous output.

When using a named expression, the expression on the right side of the := operator is always evaluated, when before a new iteration starts. Thus, the variable letters holds at most ten characters. If it is empty, the expression evaluates to False and the execution is stopped.

Groups: language reference