Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
insert()
python
communitycreator

What is array insert() in Python?

Eman Kashif

Overview

Python is a high-level programming language that provides functionalities for several operations. The array module comes with various methods to manipulate array data structures.

The array.insert(i, x) function inserts the specified value x at the index i.

Syntax

array.insert(i, x)

Arguments

  • i: The position in the array at which the value is inserted.
  • x: The specified value to be inserted.

Return value

This function does not return anything.

Code

#import module
from array import array

#initialize array with integer values
array_one = array("i", [1, 2, 3, 4, 5])

#initialize array with double values
array_two = array("d", [6.4, 2.2, 8.7])

#initialize array with double values
array_three = array("d", [5.72, 7.48, 0.43])

#initialize array with signed values
array_four = array("b", [-7, +8, -10, +14])

print (array_one)
#insert 3 at position 0
array_one.insert(0,3)
print(array_one)
print ("\n")

print (array_two)
#insert 9.8 at position 2
array_two.insert(2,9.8)
print(array_two)
print ("\n")

print (array_three)
#insert 6.45 at position 1
array_three.insert(1,6.45)
print(array_three)
print ("\n")

print (array_four)
#insert -3 at position 4
array_four.insert(4,-3)
print(array_four)
Inserting elements in an array in Python

Explanation

In the above code snippet:

  • Line 2: We import the array module.

  • Line 5: We initialize the array with integer values.

  • Line 8: We initialize the array with double values.

  • Line 14: We initialize the array with signed values.

  • Line 18: We insert value 3 at the index 0 by using array.insert().

RELATED TAGS

array
insert()
python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring