Home > Software engineering >  Python pass list as argument sends all of list data or just reference
Python pass list as argument sends all of list data or just reference

Time:05-02

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:

  1. Print test_list after the call; if the list were actually copied, the append 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 same list in the function.
  2. Print id(test_list) outside the function, and id(a) inside the function; ids are required to be unique at any given point in time, so the only way two different lists could have the same ID is if one was destroyed before the other was created; since test_list continues to exist before and after the function call, if a has the same id, it's definitionally the same list.

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].

  • Related