[Python] The difference between the list method "+" and "extend()"

List is a common data structure type
in python. It is used to append one data after the list. There is the "append()" method. There are two methods
for appending multiple data after the list. There are two methods "+" and "extend()".
The "+" is introduced below. Similarities and differences between the two methods "extend()":

1 extend() method

a = [1,2,3]
b = [4,5,6]
print("a id :",id(a))
print("b id :",id(b))

# extend()方法
a.extend(b)
print("extend: a =",a)
print("extend: a id =",id(a))

# 结果
>> a id : 139646799147568
>> b id : 139646799150128
>> extend: a = [1, 2, 3, 4, 5, 6]
>> extend: a id = 139646799147568

It can be seen that the extend() method of the list can append multiple elements in the b list to a without changing the id of a

2 List addition


a = [1,2,3]
b = [4,5,6]
print("a id :",id(a))
print("b id :",id(b))

# +
a += b
print("+: a =",a)
print("+: a id =",id(a))

# 结果
>> a id : 140080409711152
>> b id : 140080409713712
>> +: a = [1, 2, 3, 4, 5, 6]
>> +: a id = 140080409711152

It can be seen that the addition method of the list can achieve the same function without changing the id of a

3 matters needing attention

Other blogs on the Internet may say that the appending method of the list addition will change the id.
Please note that this is due to the introduction of a new list in their instance, as shown below

a = [1,2,3]
b = [4,5,6]
c = []
print("a id :",id(a))
print("b id :",id(b))
print("c id :",id(c))

# +
c = a + b
print("a =",a)
print("b =",b)
print("c =",c)
print("a id :",id(a))
print("b id :",id(b))
print("c id :",id(c))

>> a id : 140212670542384
>> b id : 140212670544944
>> c id : 140212669314064
>> a = [1, 2, 3]
>> b = [4, 5, 6]
>> c = [1, 2, 3, 4, 5, 6]
>> a id : 140212670542384
>> b id : 140212670544944
>> c id : 140212669289248

It can be seen that c is initialized to an empty list at the beginning.
After the assignment is passed, the id changes. This is the reason not explained in other posts on the Internet.

Guess you like

Origin blog.csdn.net/ao1886/article/details/109114069