国产一区二区精品-国产一区二区精品久-国产一区二区精品久久-国产一区二区精品久久91-免费毛片播放-免费毛片基地

千鋒教育-做有情懷、有良心、有品質的職業教育機構

手機站
千鋒教育

千鋒學習站 | 隨時隨地免費學

千鋒教育

掃一掃進入千鋒手機站

領取全套視頻
千鋒教育

關注千鋒學習站小程序
隨時隨地免費學習課程

當前位置:首頁  >  技術干貨  > 如何在列表中追加元素

如何在列表中追加元素

來源:千鋒教育
發布人:xqq
時間: 2023-07-21 17:00:38 1689930038

Python 提供了向列表追加或添加元素的內置方法。我們也可以將一個列表附加到另一個列表中。下面給出了這些方法。

    追加(elmt) - 它在列表末尾追加值。

    插入(index,elmt) - 它在指定的索引位置插入值。

    擴展(可迭代)- 通過添加可迭代對象擴展列表。

讓我們通過下面的例子來理解這些方法。

1.附錄(ELT)

該函數用于在列表末尾添加元素。下面給出了例子。

示例-


names = ["Joseph", "Peter", "Cook", "Tim"]

print('Current names List is:', names)

new_name = input("Please enter a name:\n")
names.append(new_name)  # Using the append() function

print('Updated name List is:', names)

輸出:

Current names List is: ['Joseph', 'Peter', 'Cook', 'Tim']
Please enter a name:
Devansh
Updated name List is: ['Joseph', 'Peter', 'Cook', 'Tim', 'Devansh']

2.插入(索引,elmt)

函數的作用是:在給定的索引位置添加元素。當我們想要在特定位置插入元素時,這是有益的。下面給出了例子。

示例-


list1 = [10, 20, 30, 40, 50]

print('Current Numbers List: ', list1)

el = list1.insert(3, 77)
print("The new list is: ",list1)

n = int(input("enter a number to add to list:\n"))

index = int(input('enter the index to add the number:\n'))

list1.insert(index, n)

print('Updated Numbers List:', list1)

輸出:

Current Numbers List:  [10, 20, 30, 40, 50]
The new list is:  [10, 20, 30, 77, 40, 50]
enter a number to add to list:
 45
enter the index to add the number:
1
Updated Numbers List: [10, 45, 20, 30, 77, 40, 50]

3.擴展(可迭代)

extends()函數用于將可迭代元素添加到列表中。它接受可迭代對象作為參數。下面是添加可迭代元素的示例。

示例-


list1 = [10,20,30]
list1.extend(["52.10", "43.12" ])  # extending list elements
print(list1)
list1.extend((40, 30))  # extending tuple elements
print(list1)
list1.extend("Apple")  # extending string elements
print(list1)

輸出:

[10, 20, 30, '52.10', '43.12']
[10, 20, 30, '52.10', '43.12', 40, 30]
[10, 20, 30, '52.10', '43.12', 40, 30, 'A', 'p', 'p', 'l', 'e']
tags: python教程
聲明:本站稿件版權均屬千鋒教育所有,未經許可不得擅自轉載。
10年以上業內強師集結,手把手帶你蛻變精英
請您保持通訊暢通,專屬學習老師24小時內將與您1V1溝通
免費領取
今日已有369人領取成功
劉同學 138****2860 剛剛成功領取
王同學 131****2015 剛剛成功領取
張同學 133****4652 剛剛成功領取
李同學 135****8607 剛剛成功領取
楊同學 132****5667 剛剛成功領取
岳同學 134****6652 剛剛成功領取
梁同學 157****2950 剛剛成功領取
劉同學 189****1015 剛剛成功領取
張同學 155****4678 剛剛成功領取
鄒同學 139****2907 剛剛成功領取
董同學 138****2867 剛剛成功領取
周同學 136****3602 剛剛成功領取
相關推薦HOT