Suppose the following 13 elements are stored in an array DATA: 11, 44, 30, 40, 55, 33, 60, 77, 22, 80, 88, 66, 99. If you are asked to insert an element 45 in 7th position, how many elements need to move to accommodate the new element? (Assume that the index of DATA array starts from 1)
Answers
As per the question, this is the array:
- [11 44 30 40 55 33 60 77 22 80 88 66 99]
To insert an element 45 in the 7th position in the array, 6 elements will need to shift to the right to accommodate the new element. The current element at the 7th position, assuming that the index starts from 0, is 77. As the question conveys, 45 is to be inserted in that position. Elements 77, 22, 80, 88, 66 and 99 will need to shift.
A Python program for the same has been created below:
We import the [NumPy - Numerical Python] module so as to create the array. Once we do, we convert it into a list as arrays are immutable and elements cannot be added to them. We use a list function, that is used to insert elements at specific index positions. Its syntax is as below:
Once we insert the element, we convert it back to an array, assigning it to a new variable. The final array is then printed.