insert an element into an array at a specific index in python

To insert an element into a specific index in a python array, you can use the insert() method. The insert() method takes two arguments: the index at which to insert the element, and the element itself.

main.py
my_array = [1, 2, 3, 4, 5]

#insert 6 at index 1
my_array.insert(1, 6)

print(my_array) #output: [1, 6, 2, 3, 4, 5]
116 chars
7 lines

In the example above, we insert the integer 6 at index 1 in the my_array list using the insert() method. The resulting list is [1, 6, 2, 3, 4, 5].

If the index specified is greater than the length of the array, the element will be appended to the end of the array.

gistlibby LogSnag