Python中的append()和extend()
列出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) 6Example 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
總結
以上是生活随笔為你收集整理的Python中的append()和extend()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AMUL的完整形式是什么?
- 下一篇: 加15的血蝴蝶之怒的号能卖多少钱