🔰Array in Python..

Ankita Patil
3 min readSep 25, 2021

Introduction and Function

What is an “Array” ?

Array is the collection of elements of similar data type stored in a single variable.

Following are the some data types and space require them in bytes.

char => 1

int => 2

short int =>2

long int =>4

long long int =>8

float =>4

double =>8

Operations on Array :

1.array(data type, value list) :- This function is used to create an array with data type and value list specified in its arguments.

import array
#Initialising array with array values
arr = array.array('i',[1,2,3,7,8,9])
#Printing original array
print("The new created array is:",end=" ")
for i in range (0,6):
print(arr[i],end=" ")
print("\r")

OUTPUT =>The new created array is: 1 2 3 7 8 9

2.append():- This function is used to add the value mentioned in its arguments at the end of the array.

#Using append() to insert new value at the end
arr.append(4);
#Printing appended array
print("The appended array is:",end=" ")
for i in range(0,7):
print(arr[i],end=" ")
print("\r")

OUTPUT =>The appended array is: 1 2 3 7 8 9 4

3.insert(i,x) :- This function is used to add the value(x) at the i th position specified in its argument.

#Using insert() to insert value at specific position
#Here we are inserting 5 at 2nd position
arr.insert(2,5)
print("\r")#Printing array after insertion
print("The array after insertion is:",end=" ")
for i in range(0,8):
print(arr[i],end=" ")

OUTPUT =>The array after insertion is: 1 2 5 3 7 8 9 4

4.pop():- This function removes the element at the position mentioned in its argument and returns it.

# using pop() to remove element at 2nd position
print ("The popped element is : ",end="")
print (arr.pop(2));

# printing array after popping
print ("The array after popping is : ",end="")
for i in range (0,7):
print (arr[i],end=" ")
print("\r")

OUTPUT =>The popped element is : 5
The array after popping is : 1 2 3 7 8 9 4

5.remove():- This function is used to remove the first occurrence of the value mentioned in its arguments.

# using remove() to remove 1st occurrence of 1
arr.remove(1)

# printing array after removing
print ("The array after removing is : ",end="")
for i in range (0,6):
print (arr[i],end=" ")

OUTPUT =>The array after removing is : 2 3 7 8 9 4

6.index():- This function returns the index of the first occurrence of value mentioned in arguments.

# Using index() to print index of 1st occurance of 2
print("The index of 1st occurance of 2 is:",end=" ")
print(arr.index(2))

OUTPUT =>The index of 1st occurance of 2 is: 0

7.reverse():- This function reverses the array.

#Using reverse() to reverse the array
arr.reverse()
#Printing array after reversing
print("The array after reversing is:",end=" ")
for i in range(0,6):
print(arr[i],end=" ")

OUTPUT =>The array after reversing is: 4 9 8 7 3 2

Hope this blog is helpful to you to clear your concepts..😉🙌

Thanks for reaching here…!!😊

--

--