列出append()方法 (List append() method)
append() method is used to insert an element or a list object to the list and length of the List increased by the 1.
append()方法用于将元素或列表对象插入列表,并且列表长度增加1。
Syntax:
句法:
List.append(element/object)
Example 1:
范例1:
# declaring a list
list1 = [10, 20, 30, 40, 50]
# printing the list before appending
print("list1: ", list1)
print("len(list1): ", len(list1))
# appending an element to the list
list1.append(60)
# printing the list after appending
print("list1: ", list1)
print("len(list1) ", len(list1))
Output
输出量
list1: [10, 20, 30, 40, 50]
len(list1): 5
list1: [10, 20, 30, 40, 50, 60]
len(list1) 6
Example 2:
范例2:
# declaring a list
list1 = [10, 20, 30, 40, 50]
# printing the list before appending
print("list1: ", list1)
print("len(list1) ", len(list1))
# appending a list object to the list
list2 = [60, 70, 80]
list1.append(list2)
# printing the list after appending
print("list1: ", list1)
print("len(list1) ", len(list1))
Output
输出量
list1: [10, 20, 30, 40, 50]
len(list1) 5
list1: [10, 20, 30, 40, 50, [60, 70, 80]]
len(list1) 6
列出extend()方法 (List extend() method)
extend() method is used to extend the list by inserting the given number of elements or given list and the length of the List increased by the total number of elements added.
extend()方法用于通过插入给定数量的元素或给定列表来扩展列表,并且List的长度增加所添加元素的总数。
Syntax:
句法:
List.extend(another_list)
Note: If we append a list, then the list appended as an element to the List, thus, the length of the list increased by 1. While, if we extend a list by a list, then the list extended by the given number of elements in the list (which is passed as an argument), thus, the length of the list increased by the given number of elements in the list which is going to be added.
注意:如果我们添加一个列表,那么该列表作为元素添加到列表中,因此,列表的长度增加了1。而如果我们将列表扩展了一个列表,则该列表扩展了给定数量的列表中的元素(作为参数传递),因此,列表的长度增加了列表中要添加的元素的给定数量。
Example:
例:
# declaring a list
list1 = [10, 20, 30, 40, 50]
# printing the list before extending
print("list1: ", list1)
print("len(list1) ", len(list1))
# extending the list with another list
list2 = [60, 70, 80]
list1.extend(list2)
# printing the list after extending
print("list1: ", list1)
print("len(list1) ", len(list1))
翻译自: https://www.includehelp.com/python/append-and-extend.aspx