Python-list 中 append()和extend()的区别

    (1) append(object) -> None -- append object to end

          append(object) 是将一个对象作为一个整体添加到列表中,添加后的列表比原列表多一个元素,该函数的参数可以是任何类型的对象,该函数没有返回值          

    (2) extend(iterable) -> None -- extend list by appending elements from the iterab

          extend(iterable) 是将一个可迭代对象中的每个元素逐个地添加到列表中,可迭代对象中有几个元素,添加后的列表就比原列表多几个元素,该函数的参数必须是可迭代的对 象,改函数没有返回值
 

>>> listA = [1, 2, 3]
>>> listB = [4, 5, 6]
>>> listA.append(listB)
>>> print(listA)
[1, 2, 3, [4, 5, 6]]
>>> listA.extend(listB)
[1, 2, 3, [4, 5, 6], 4, 5, 6]
>>> listB.append(7)
>>> print(listB)
[4, 5, 6, 7]
>>> listB.append({'a':97, 'b':98})
>>> print(listB)
[4, 5, 6, 7, {'a': 97, 'b': 98}]
>>> listB.extend('def')
>>> print(listB)
[4, 5, 6, 7, {'a': 97, 'b': 98}, 'd', 'e', 'f']

转载地址:https://blog.csdn.net/sushiqian/article/details/78347813

猜你喜欢

转载自blog.csdn.net/weixin_40446557/article/details/87937145