Python列表extend与append方法的区别详解
本文详细解析Python中列表的append和extend方法。append仅接受单个参数并添加至末尾,而extend接收一个列表参数并将其中元素逐一追加。通过具体代码示例对比两者在参数数量、处理单个对象与列表时的行为差异,帮助开发者准确选择合适的方法。
append() 方法用于向列表尾部追加一个单一的新元素,该方法仅接受一个参数。
>>> num = [1,2]
>>> num.append(3)
>>> num
[1, 2, 3]
>>> num.append('a')
>>> num
[1, 2, 3, 'a']
>>> num.append(6,7)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
num.append(6,7)
TypeError: append() takes exactly one argument (2 given)
>>> num.append([6])
>>> num
[1, 2, 3, 'a', [6]]
>>> num.append({'a'})
>>> num
[1, 2, 3, 'a', [6], set(['a'])]
extend() 方法同样只接受一个参数,但该参数必须是一个列表。它会将该列表中的每个元素分别添加到原有列表的末尾。
>>> num=[1,2] >>> num.extend([5]) >>> num [1, 2, 5] >>> num.extend(['b']) >>> num [1, 2, 5, 'b'] >>> num.extend(6,7) Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> num.extend(6,7) TypeError: extend() takes exactly one argument (2 given)
总结
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。如果你想了解更多相关内容请查看下面相关链接
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









