Python - 陣列 insert() 方法



Python 陣列的 insert() 方法用於在指定位置(即索引值)插入或新增元素。

索引值從零開始。當我們插入一個元素時,序列中所有現有的元素都會向右移動以容納新元素。

語法

以下是 Python 陣列 insert() 方法的語法:

array_name.insert(position,element)

引數

此方法接受兩個引數:

  • position:表示需要插入元素的索引位置。
  • element:表示要插入陣列的值。

返回值

此方法不返回值。

示例 1

以下是 Python 陣列 insert() 方法的基本示例:

import array as arr
#Creating an array
my_array1 = arr.array('i',[10,20,30,40])
#Printing the elements of an array
print("Array Elements Before Inserting : ", my_array1)
element1=100
position1=2
my_array1.insert(position1,element1)
print("Array Elements After Inserting : ", my_array1)

輸出

element1 在 my_array1 的 position1 位置插入。以下是輸出:

Array Elements Before Inserting :  array('i', [10, 20, 30, 40])
Array Elements After Inserting :  array('i', [10, 20, 100, 30, 40])

示例 2

如果陣列和插入元素的資料型別不同,則會得到 typeerror 錯誤。

在下面的示例中,我們建立了一個 int 資料型別的陣列,嘗試插入 float 值:

import array as arr
#Creating an array
my_array2 = arr.array('i',[11,340,30,40])
#Printing the elements of an array
print("Array Elements Before Inserting : ", my_array2)
#element that to be inserted
element2=14.5
#position at which element to be inserted
position2=3
#insertion of element1 at position
my_array2.insert(position2,element2)
print("Array Elements After Inserting : ", my_array2)

輸出

Array Elements Before Inserting :  array('i', [11, 340, 30, 40])
Traceback (most recent call last):
  File "E:\pgms\insertprg.py", line 27, in <module>
    my_array2.insert(position,element1)
TypeError: 'float' object cannot be interpreted as an integer

示例 3

如果我們向陣列中插入任何可迭代物件,例如元組或列表,則會得到錯誤。

在這裡,我們嘗試將 element3(一個 tuple)插入到陣列 my_array3 中,結果導致錯誤:

import array as arr
#Creating an array
my_array3 = arr.array('i',[191,200,330,540])
#Printing the elements of an array
print("Array Elements Before Inserting : ", my_array3)
element3=(10,100,100)
position3=2
my_array3.insert(position3,element3)
print("Array Elements After Inserting : ", my_array3)

輸出

Array Elements Before Inserting :  array('i', [191, 200, 330, 540])
Traceback (most recent call last):
  File "E:\pgms\insertprg.py", line 53, in <module>
    my_array3.insert(position3,element3)
TypeError: 'tuple' object cannot be interpreted as an integer

示例 4

在此示例中,我們可以使用負索引插入元素。讓我們透過以下示例來理解:

import array as arr
#Creating an array
my_array4 = arr.array('i',[11,340,30,40,100,50,34,24,9])
#Printing the elements of an array
print("Array Elements Before Inserting : ", my_array4)
element4 = 878
position = -1
my_array4.insert(position,element4)
print("Array Elements After Inserting : ", my_array4)

輸出

以下是上述程式碼的輸出:

Array Elements Before Inserting :  array('i', [11, 340, 30, 40, 100, 50, 34, 24, 9])
Array Elements After Inserting :  array('i', [11, 340, 30, 40, 100, 50, 34, 24, 878, 9])
python_array_methods.htm
廣告