Explanation
๐น Step 1: Create List
x = [1,2,3]
A list is created:
[1,2,3]
Length of list:
3
๐น Step 2: Understand Walrus Operator :=
n := len(x)
This is called the Walrus Operator.
Normal way:
n = len(x)
print(n)
Walrus way:
print(n := len(x))
It does two things at the same time:
1️⃣ Assigns value
n = 3
2️⃣ Returns that value
3
๐น Step 3: Evaluate len(x)
len(x)
Length of:
[1,2,3]
is:
3
๐น Step 4: Execute Walrus Assignment
n := 3
Python stores:
n = 3
and returns:
3
Now memory contains:
n = 3
๐น Step 5: Evaluate Print Arguments
First argument:
(n := len(x))
becomes:
3
Second argument:
n
already contains:
3
So Python sees:
print(3, 3)
๐น Step 6: Print Result
print(3, 3)
Output:
3 3

0 Comments:
Post a Comment