Sequence objects-+ and +=, extend and append
1. The difference between + and += in sequence operations
a = [1,2]
c = a + [3,4]
print(c) # [1,2,3,4]
# += 可以想成是就地加
a += [3,4]
print(a) # [1,2,3,4]
a = [1,2]
c = a + (3,4)
print(c) # TypeError : can only concatenate list (not "tuple") to list
a += (3,4)
print(a) # [1,2,3,4]
+=
+
There is a big difference between notation and sequence operations.
+=
The symbol object can be any sequence type (tuple or list, etc.) in sequence operations. The +
symbol can only be two sequence objects of the same type.
Because the +=
symbol is actually realized by a magic function abc
, there is a MutableSequence
class (variable sequence) in the module in the source code , which has a __iadd__
magic function called . So when we use +=
symbols, we are actually calling the logic in this function.
def __iadd__(self, values):
self.extend(values)
return self
In the __iadd__
magic function, it will call the extend
method, which will receive a value
value. Then use the for
loop (for sequence types can use for) to put the elements append
into the sequence one by one . extend
Received is an iterable object.
def extend(self, values):
'S.extend(iterable) -- extend sequence by appending elements from the iterable'
for v in values:
self.append(v)
2. The difference between extend and append
As mentioned at the end of section 1, the extend
method will for
loop through each element in the sequence and add them to the sequence object.
a = [1,2]
a += (3,4)
# a.extend([6, 7, 8]) # [1, 2, 3, 4, 6, 7, 8]
# a.extend((6, 7, 8)) # [1, 2, 3, 4, 6, 7, 8]
a.extend(range(3))
print(a) # [1,2,3,4,0,1,2]
The append
method adds the input as a whole.
a = [1,2]
# a.append((1,2)) # [1, 2, (1, 2)]
a.append([1,2])
print(a) # [1, 2, [1, 2]]