OneBite.Dev - Coding blog in a bite size

insert an element at the beginning of an array in python

Code snippet on how to insert an element at the beginning of an array in python

arr = [3,4,5] 
# Insert the number 2 at the beginning of the array
arr.insert(0,2) 

print(arr) 

This code inserts the number 2 at the beginning of the array. The first line of code creates an array named ‘arr’ and stores the elements 3, 4 and 5 inside of it. The second line of code uses the ‘insert’ method to add the number 2 to the beginning of the array. The 0 parameter indicates that the element should be added at index 0, and the 2 parameter is the element that is to be added. Finally, the third line of code prints the array to the console. The output would be [2,3,4,5].

python