I have the following code:
def test(a):
a.append(3)
test_list = [1,2]
test(test_list)
In the above code, when I pass test_list as an argument to test function, does python send the whole list object/data (which is a big byte size) or just the reference to the list (which would be much smaller since its just a pointer)?
From what I understood by looking at Python's pass by object reference, it only sends the reference, but do not know how to verify that it indeed is the case
CodePudding user response:
It's passing an alias to the function; for the life of the function, or until the function intentionally rebinds a
to point to something else (with a = something
), the function's a
is an alias to the same list
bound to the caller's test_list
.
The straightforward ways to confirm this are:
- Print
test_list
after the call; if thelist
were actually copied, theappend
in the function would only affect the copy, the caller wouldn't see it.test_list
will in fact have had a new element appended, so it was the samelist
in the function. - Print
id(test_list)
outside the function, andid(a)
inside the function;id
s are required to be unique at any given point in time, so the only way two differentlist
s could have the same ID is if one was destroyed before the other was created; sincetest_list
continues to exist before and after the function call, ifa
has the sameid
, it's definitionally the samelist
.
CodePudding user response:
All function arguments are passed by reference in Python. So the a
variable in the function test
will refer to the same object as test_list
does in the calling code. After the function returns, test_list
will contain [1,2,3]
.