python list parameter?

I recently encountered an interesting problem. When a list is passed to a function as a parameter, different operations in the function body will affect the original list.

Use append/extend in the function body:

l1=[1,2,3,4]
def test(l2):
    l2.append(333)
    print("l2:", l2)
test(l1)
print("l1:",l1)

>>>
l2: [1, 2, 3, 4, 333]
l1: [1, 2, 3, 4, 333]
l1=[1,2,3,4]
def test(l2):
    l2.extend([333])
    print("l2:", l2)
test(l1)
print("l1:",l1)

>>>
l2: [1, 2, 3, 4, 333]
l1: [1, 2, 3, 4, 333]

Use + in the function body:

l1=[1,2,3,4]
def test(l2):
    l2=l2+[333]
    print("l2:", l2)
test(l1)
print("l1:",l1)

>>>
l2: [1, 2, 3, 4, 333]
l1: [1, 2, 3, 4]

Guess you like

Origin blog.csdn.net/weixin_43732022/article/details/131722131