Am 25.05.21 um 06:08 schrieb hw:
On 5/25/21 12:37 AM, Greg Ewing wrote:
Python does have references to *objects*. All objects live on
the heap and are kept alive as long as there is at least one
reference to them.

If you rebind a name, and it held the last reference to an
object, there is no way to get that object back.

Are all names references?  When I pass a name as a parameter to a function, does the object the name is referring to, when altered by the function, still appear altered after the function has returned?  I wouldn't expect that ...


Yes, it does. It is a common pitfall for newbie Python programmers.

def f(a):
        a.append(2)

l=[1, 2, 3]

f(l)
print(l)


==> [1, 2, 3, 2]

The strange thing, coming from a different language, is the apparent difference, if instead of a list, you pass an integer:

def f(a):
        a=5

l=3

f(l)
print(l)

====> 3

Here, the "l" is not changed. The reason is that the statement "a=5" does NOT modify the object in a, but instead creates a new one and binds it to a. l still points to the old one. Whereas a.append() tells the object pointed to by a to change.

        Christian

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to