5

How to Pass List by Value as Parameter in Python

 2 years ago
source link: https://jdhao.github.io/2022/07/27/pass_list_by_value_python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Pass List by Value as Parameter in Python

2022-07-27 171 words 1 min read 48 times read

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

Author jdhao

LastMod

2022-07-27

License CC BY-NC-ND 4.0

Reward

Prev

Next

Powered by Hugo

|

Theme - Even

site pv: 3326823 | site uv: 2503906

© 2017 - 2022jdhao


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK