Post History
Assignment expressions (Python 3.8+) The assignment expression (aka the walrus operator) := was introduced in Python 3.8 as a result of PEP 572, which can be used inline to assign a variable as pa...
#1: Initial revision
# Assignment expressions (Python 3.8+)
The assignment expression (aka the walrus operator) `:=` was introduced in Python 3.8 as a result of [PEP 572], which can be used inline to assign a variable as part of an expression, like so:
```python
>>> (n:=2, n+5)
(2, 7)
```
This can be used in a comprehension to update some value iteratively, and actually stores the result after each iteration. For example, computing the sum of the first 50 cubes by updating the total `t`:
```python
>>> t=0
>>> l=[*range(51)]
>>> print([t:=t+x**3 for x in l])
[0, 1, 9, 36, 100, 225, 441, 784, 1296, 2025, 3025, 4356, 6084, 8281, 11025,
14400, 18496, 23409, 29241, 36100, 44100, 53361, 64009, 76176, 90000, 105625,
123201, 142884, 164836, 189225, 216225, 246016, 278784, 314721, 354025,
396900, 443556, 494209, 549081, 608400, 672400, 741321, 815409, 894916,
980100, 1071225, 1168561, 1272384, 1382976, 1500625, 1625625]
>>> t
1625625
```
Or, say you want to print the numbers from 0 to 100 without using the number 1-9. While this is possible to do in Python 3 in 20 bytes (this has been [done](https://codegolf.stackexchange.com/a/236729/120105) [twice](https://codegolf.stackexchange.com/a/219577/120105) on CG&CC Stack Exchange), it can also be done with the usage of assignment operators in 46:
```python
print(*range(-~((m:=-~((n:=-~-~0)*n))*m*n*n)))
```
Explanation:
```python
print(*range(-~((m:=-~((n:=-~-~0)*n))*m*n*n))) # program
n:=-~-~0 # Set n=2, since-~x == x+1
(n:=-~-~0)*n # (n:=2)*2 == 4
m:=-~((n:=-~-~0)*n) # m:=(n:=2)*n+1 == 5
(m:=-~((n:=-~-~0)*n))*m*n*n # 5 * 5 * 2 * 2 == 100
-~((m:=-~((n:=-~-~0)*n))*m*n*n) # 100 + 1 == 101.
range(-~((m:=-~((n:=-~-~0)*n))*m*n*n)) # range from 0 to 101-1==100
print(*range(-~((m:=-~((n:=-~-~0)*n))*m*n*n)) # print the numbers from
# 0 to 100, separated by
# spaces.
```
If all numbers cannot be used, we only really lose 1 byte, because in Python, `True == 1` and `False == 0`:
```python
print(*range(-~((m:=-~((n:=-~True)*n))*m*n*n)))
```
[PEP 572]:https://www.python.org/dev/peps/pep-0572/
