序列的+、+=、extend、append理解
列表 + 元组:
1 >>> a = [1, 2] 2 >>> b = (3, 4) 3 >>> a = a + b 4 Traceback (most recent call last): 5 File "<stdin>", line 1, in <module> 6 TypeError: can only concatenate list (not "tuple") to list
列表 += 元组:
1 >>> a += b 2 >>> a 3 [1, 2, 3, 4]
原因:‘ += ’是调用 iadd()函数,然后调用extend函数,extend函数会遍历序列元素再依次加入:
def __iadd__(self, values): self.extend(values) return self def extend(self, values): 'S.extend(iterable) -- extend sequence by appending elements from the iterable' for v in values: self.append(v)
append()始终将加入的元素作为整体加入:
1 >>> a 2 [1, 2, 3, 4] 3 >>> a.append((5, 6)) 4 >>> a 5 [1, 2, 3, 4, (5, 6)]
Talk is cheap, show my code to you.