Both methods append() and extend() are used to insert elements in a list.
方法append()和extend()都用于在列表中插入元素。
append():
附加():
append() method appends the object at the end i.e. it appends argument as a single element at the end of the list.
append()方法将对象追加到末尾,即,将参数作为单个元素追加到列表的末尾。
Syntax:
句法:
list.append(object)
Example:
例:
list1 = [10, 20, 30]
list2 = [40, 50, 60]
# printing the list before
# append() operation
print("list1:", list1)
print("list2:", list2)
# appending the list2 in list1
list1.append(list2)
# printing the list
print("After append, list1:", list1)
Output:
输出:
list1: [10, 20, 30]
list2: [40, 50, 60]
After append, list1: [10, 20, 30, [40, 50, 60]]
See the output, list2 is added as an object in the list1.
参见输出,将list2作为对象添加到list1中 。
extend():
延伸():
extend() method extends the list by appending the elements of the given object/iterable i.e. it appends argument as elements at the end of the list.
extend()方法通过添加给定对象/可迭代对象的元素来扩展列表,即,将参数作为元素添加到列表的末尾。
Syntax:
句法:
list.extend(object)
Example:
例:
list1 = [10, 20, 30]
list2 = [40, 50, 60]
# printing the list before
# extend() operation
print("list1:", list1)
print("list2:", list2)
# appending the list2 in list1
list1.extend(list2)
# printing the list
print("After extend, list1:", list1)
Output:
输出:
list1: [10, 20, 30]
list2: [40, 50, 60]
After extend, list1: [10, 20, 30, 40, 50, 60]
See the output, list2 is added as elements in the list1.
参见输出,将list2作为元素添加到list1中 。
Conclusion:
结论:
Thus, the basic difference is between append() and extend() method is that append() appends the argument as an object while extend() appends the argument as elements.
因此, append()和extend()方法之间的基本区别在于 , append()将参数作为对象附加,而extend()将参数作为元素附加。
Read more: append() and extend() in Python
阅读更多: Python中的append()和extend()
翻译自: https://www.includehelp.com/python/difference-between-pythons-list-methods-append-and-extend.aspx