The difference between +, += and extend and append of sequence objects in python

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 MutableSequenceclass (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 extendmethod, which will receive a valuevalue. Then use the forloop (for sequence types can use for) to put the elements appendinto the sequence one by one . extendReceived 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 extendmethod will forloop 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 appendmethod 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]]

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106974206