Skip to main content
  1. Posts/

How to Pass List by Value as Parameter in Python

··172 words·1 min·
Python
Table of Contents

If we pass list as parameter to a function and change the parameter, the original list is also changed. This is because list is a mutable type, when we pass list to a function, we are passing the same list.

def my_fun(my_list):
    my_list.append(1)

    return my_list


x = [1, 2, 3]
y = my_fun(x)

print(f"x: {x}, y: {y}")
# x, y are both [1, 2, 3, 1]

How can we pass the “value” of this list instead of its “reference”? We can use several ways:

  • slicing: my_fun(x[:])
  • list(): my_fun(list(x))
  • list.copy(): my_fun(x.copy())
  • copy.copy(): my_fun(copy.copy(x))
  • copy.deepcopy(): my_fun(copy.deepcopy(x))

The first four ways only create a shallow copy of the original list. They only work for simple list consisting of immutable types, for example, a list of int. If the list element is a mutable type themselves, they will not work.

Only the copy.deepcopy() method can truly create a new list.

references
#

Related

Retry for Google Cloud Client
·197 words·1 min
Python GCP
Make Python logging Work in GCP
·570 words·3 mins
Python Logging GCP
Speed up document indexing in Elasticsearch via bulk indexing
·355 words·2 mins
Python Elasticsearch