Array Operations In Python (without Using Any Predefined Functions)

Array Operations In Python (without Using Any Predefined Functions)

ARRAY

Arrays are fundamental data structures used to store collections of items. In Python, arrays are implemented using lists. An array is a collection of elements, each identified by at least one array index or key. These elements are stored in contiguous memory locations(memory addresses of consecutive elements in memory are next to each other without any gaps), allowing for efficient access to each element based on its index.

I am going to do the following operations without using any pre defined functions,

  1. Traversal: Iterating through each element in the array.

  2. Insertion: Adding a new element to the array.

  3. Deletion: Removing an element from the array.

  4. Update: Modifying an existing element in the array.

  5. Search: Finding the position of a specific element in the array.

TRAVERSE (ACCESS)

Accessing each element in the array.

# traverse
from array import array as ar
a=ar('i',[1,2,3,4,5])
print(type(a))
a=ar('i',[1,2,3,4,5])
for i in range(len(a)):
    print("position ",i," value is ",a[i])
OUTPUT:
position  0  value is  1
position  1  value is  2
position  2  value is  3
position  3  value is  4
position  4  value is  5

INSERTION

Insert a new element at ta particular position in the array.

a=ar('i',[1,2,3,4,5])
pos=2 # 2nd position in the array
val=1000
for i in range(len(a)-1,pos-1):
    a[i]=a[i-1]
a[pos-1]=val
for i in a:
    print(i,end="")
OUTPUT:
1 1000 3 4 5

DELETE

Removing an element from the array

# search
a=ar('i',[1,2,3,4,5])
f=3
i=0
while(len(a)>0):
    if a[i]==f:
        print("pos ",i,"value ",a[i])
        break
    i=i+1
else:
    pass
OUTPUT:
pos  2 value  3

UPDATE

Modifying an existing element in the array

# update and element
a=ar('i',[1,2,3,4,5])
pos=3
val=1000
a[pos]=val
print(a)
OUTPUT:
array('i', [1, 2, 3, 1000, 5])

Finding the position of a specific element in the array

a=ar('i',[1,2,3,4,5])
f=3
i=0
while(len(a)>0):
    if a[i]==f:
        print("pos ",i,"value ",a[i])
        break
    i=i+1
else:
    pass
OUTPUT:
pos  2 value  3