Skip to content

2. Assignments

Crowthebird edited this page Sep 8, 2021 · 2 revisions

The Walrus Operator

In Python 3.8, an operator was added, called the walrus operator (:=, officially called an Assignment Expression), to be used to assign to names (variables) in expressions. But unfortunately, it cannot assign to attribute access (x.attribute) or subscripting (x[0]). It can be especially useful for esoteric code, because it can assign to the local namespace without raising a SyntaxError.

Figure 2.1
a = 2 + (b = 4) # `SyntaxError`
a = 2 + (b := 4) # No problem
print(a) # 6
print(b) # 4
Figure 2.2
a = (b := 5, 4,)
c = (d := (5, 4),)
e = ((f := 5, 4),)
print(a, b) # (5, 4) 5
print(c, d) # ((5, 4),) (5, 4)
print(e, f) # ((5, 4),) 5

The Comprehension Assignment

Another way to assign to something the esoteric way is using comprehensions. Yep, those generators or list comprehensions or set comprehensions or dict comprehensions. They are used somewhat like this—

l = [...]
b = [... for l[0] in [1]]
print(l[0]) # 1

Figure 2.3

—or like this:

l = [..., ...]
_ = [... for [l[0], l[1]] in [[1, 2]]]
print(l) # [1, 2]

Figure 2.4

Assign to an empty dictionary? No problem:

d = {}
_ = [... for d['hah'] in [1]]
print(d) # {'hah': 1}

Figure 2.5

Tried to assign to an empty list?

Although it may seem like you can assign to an empty list index using this, you cannot. Python does not allow assigning to an empty list index so there are "no holes" in a list. You may only do this in a dictionary, where the keys are unordered, and since a 'tuple' object does not support item assignment.


Clone this wiki locally