3 ms·
In Python, variable names do not directly contain their values. Instead, in your memory (on "the heap") there are "boxes". You can visualize them like cardboard
by psyklic 4y ago
In Python, variable names do not directly contain their values. Instead, in your memory (on "the heap") there are "boxes". You can visualize them like cardboard boxes that contain values. In Python, these boxes are called "objects".
Variable names merely point to these boxes. They can be bound to boxes (`a = 9999` -- here, evaluating 9999 creates a box) and unbound from boxes (`del a`). The boxes exist independently of the variable names -- at least until they are no longer bound to, at which point they may be "thrown out" (deallocated) by the garbage collector.
>> Interestingly, in CPython you can see the "address" of the box `a` is bound to by evaluating `id(a)`.
With this in mind, let's try the given example. In the first assignment `a = [1, 2, 3, 4]`, the right-hand side (RHS) is evaluated first. This creates a "box" in memory that contains the list (see Note). So, visualize that the RHS evaluates to this newly created "box" in memory. Then the name `a` is bound to it (alternatively, "points"/"refers" to it).
When we `return a`, first `a` is evaluated. It is evaluated to be the "box" in memory. Just for comparison, suppose we instead `return 9999`. Similarly here, 9999 evaluates to a newly-created "box" (which contains the int value 9999).
So now let's call the function `result = func(5)`. First, the RHS is evaluated to be the "box" referred to in the return statement. Finally, the variable `result` is bound to that box. This is actually how all assignments work -- the RHS is evaluated to a box, and the variable name is bound to the box!
>> So if we evaluate `b = a`, then both variable names end up pointing to the box referred to by `a`. You can verify this easily: `id(a) == id(b)`.
(Note) Technically, a list is represented by one box. However, each element also requires at least one additional box. (In coding-speak we say a list is a "collection" of objects.)
- noob_eng 4y agoFantastic explanation. My doubt was half cleared by skrishnamurthi. You cleared it entirely. Thanks.