千鋒教育-做有情懷、有良心、有品質(zhì)的職業(yè)教育機構(gòu)

手機站
千鋒教育

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

千鋒教育

掃一掃進入千鋒手機站

領(lǐng)取全套視頻
千鋒教育

關(guān)注千鋒學習站小程序
隨時隨地免費學習課程

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

如何在列表中追加元素

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

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

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

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

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

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

1.附錄(ELT)

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

示例-


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)

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

示例-


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()函數(shù)用于將可迭代元素添加到列表中。它接受可迭代對象作為參數(shù)。下面是添加可迭代元素的示例。

示例-


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教程
聲明:本站稿件版權(quán)均屬千鋒教育所有,未經(jīng)許可不得擅自轉(zhuǎn)載。
10年以上業(yè)內(nèi)強師集結(jié),手把手帶你蛻變精英
請您保持通訊暢通,專屬學習老師24小時內(nèi)將與您1V1溝通
免費領(lǐng)取
今日已有369人領(lǐng)取成功
劉同學 138****2860 剛剛成功領(lǐng)取
王同學 131****2015 剛剛成功領(lǐng)取
張同學 133****4652 剛剛成功領(lǐng)取
李同學 135****8607 剛剛成功領(lǐng)取
楊同學 132****5667 剛剛成功領(lǐng)取
岳同學 134****6652 剛剛成功領(lǐng)取
梁同學 157****2950 剛剛成功領(lǐng)取
劉同學 189****1015 剛剛成功領(lǐng)取
張同學 155****4678 剛剛成功領(lǐng)取
鄒同學 139****2907 剛剛成功領(lǐng)取
董同學 138****2867 剛剛成功領(lǐng)取
周同學 136****3602 剛剛成功領(lǐng)取
相關(guān)推薦HOT
久久亚洲中文字幕精品一区四,亚洲日本另类欧美一区二区,久久久久久久这里只有免费费精品,高清国产激情视频在线观看
免费h片网站在线观看视频 原创国产中文AV | 综合卡通欧美日韩亚洲 | 亚洲综合中文字幕无线码 | 亚洲国产无色码在线播放 | 亚洲国产精品一区二区尤物 | 亚洲日本中文字幕天堂网 |