Changing the value of lists as function arguments

I know when you send a list as a parameter to a function, changes to the function change the list, for example:

p=[[3, 4], [2, 3]]
node=[5,3]

def foo(node, p_as_list):
    p_as_list.append(node)


foo(node, p)
print(p) #p changes

to stop the changes I used copy ():

p=[[3, 4], [2, 3]]
node=[5,3]

def foo(node, p_as_list):
    p_as_list.append(node)

#this line
foo(node, p.copy())
print(p) # without changes

but if I change the function as follows:

p=[[3, 4], [2, 3]]
node=[5,3]

def foo(node, p_as_list):
    #this line
    p_as_list=p_as_list[-1]
    p_as_list.append(node)

foo(node, p.copy())
print(p) 

p will change again, I cannot understand why this is happening?

+4
source share
2 answers

Inserting some debugging printhelps identify the problem:

p=[[3, 4], [2, 3]]
node=[5,3]

def foo(node, p_as_list):
    #this line
    print('p', id(p_as_list))
    p_as_list=p_as_list[-1]
    print('pm1', id(p_as_list))
    p_as_list.append(node)

print('p', id(p))
print('pm1', id(p[-1]))
foo(node, p.copy())
print(p) 

this prints:

p 1872370555144 
pm1 1872370556232
p 1872370108872
pm1 1872370556232
[[3, 4], [2, 3, [5, 3]]]

Please note that idof has p[-1]not changed, you are working with the same list. This is because you create a shallow copy only when used list.copy()!

copy , :

p=[[3, 4], [2, 3]]
node=[5,3]

def foo(node, p_as_list):
    #this line
    p_as_list=p_as_list[-1].copy()  # copy here!
    p_as_list.append(node)

foo(node, p)  # don't copy here!
print(p) 
+1

- deepcopy

: https://docs.python.org/2/library/copy.html

import copy

p = [[3, 4], [2, 3]]
node = [5,3]

def foo(node, p_as_list):
    p_as_list = p_as_list[-1]
    p_as_list.append(node)

foo(node, copy.deepcopy(p))

print(p)
0

Source: https://habr.com/ru/post/1664163/


All Articles