日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python | 在列表中指定索引处添加元素的程序

發(fā)布時(shí)間:2025/3/11 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python | 在列表中指定索引处添加元素的程序 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Given a list and we have to add an element at specified index in Python.

給定一個(gè)列表,我們必須在Python中的指定索引處添加一個(gè)元素。

list.appened() Method is used to append/add an element at the end of the list. But, if we want to add an element at specified index, we use insert() method. It takes 2 arguments, index and element.

list.appened()方法用于在列表末尾添加/添加元素。 但是,如果要在指定的索引處添加元素,則可以使用insert()方法。 它需要2個(gè)參數(shù), index和element 。

Syntax:

句法:

list.insert(index, element)

Here,

這里,

  • list is the name of the list, in which we have to insert element at given index.

    list是列表的名稱,我們必須在其中給定index插入元素 。

  • index is the position, where we want to insert an element.

    index是我們要插入元素的位置。

  • element is an element/item to be inserted in the list.

    element是要在列表中插入的元素/項(xiàng)目。

Example:

例:

list.insert(2, 100)It will insert 100 at 2nd position in the list name ‘list’.

Program:

程序:

# Declaring a list list = [10, 20, 30]# printing elements print (list) # O/P will be: [10, 20, 30]# inserting "ABC" at 1st index list.insert (1, "ABC") # printing print (list) # O/P will be: [10, 'ABC', 20, 30]# inserting "PQR" at 3rd index list.insert (3, "PQR") # printing print (list) # O/P will be: [10, 'ABC', 20, 'PQR', 30]# inserting 'XYZ' at 5th index list.insert (5, "XYZ") print (list) # O/P will be: [10, 'ABC', 20, 'PQR', 30, 'XYZ']# inserting 99 at second last index list.insert (len (list) -1, 99) # printing print (list) # O/P will be: [10, 'ABC', 20, 'PQR', 30, 99, 'XYZ']

Output

輸出量

[10, 20, 30][10, 'ABC', 20, 30][10, 'ABC', 20, 'PQR', 30][10, 'ABC', 20, 'PQR', 30, 'XYZ'][10, 'ABC', 20, 'PQR', 30, 99, 'XYZ']

翻譯自: https://www.includehelp.com/python/add-an-element-at-specified-index-in-a-list.aspx

總結(jié)

以上是生活随笔為你收集整理的Python | 在列表中指定索引处添加元素的程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。