Skip to main content
  1. Posts/

How to Pass List by Value as Parameter in Python

··172 words·1 min·
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

Configure Python logging with dictConfig
··503 words·3 mins
How to Profile Your Python Script/Module
·328 words·2 mins
How to Deploy Fastapi Application with Docker
·508 words·3 mins