Python Arrays




1.       Write a program to create one array from another array.


from array import *
a1=array('i',[1,2,3,4,5])
a2=array(a1.typecode, (a for a in a1))
print(a1)
print("The program created from another array")
print(a2)



2. Create a program to retrieve, display and update only a range of elements from an array using indexing and slicing in arrays.


from array import *
x= array('i',[1,2,3,4,5,6,7,8,9,10])
#Slicing
y=x[2:4]
print('slicing',y)
x[0]=5
print('updated array', x)


3.    Write a program to understand various methods of array class mentioned: append, insert, remove, pop, index, tolist and count.

from array import *
a=array('i',[1,2,3,4,5])
print("Original array ",a)
a.append(10)
a.append(20)
print("After appending 10 and 20 the array is ",a)
x=int(input("Enter no. u want to count from array"))
print("The occurance of ",x ,"is ",a.count(x))

b=array('i',[6,7,8,9])
a.extend(b)
print("The array after extending b" , a)
print("The index position of 5 in array " , a.index(5))
a.insert(0,11)
print ("Insert 11 at 0 the position in array  ", a)
a.pop()
print("The array after pop function", a)
a.pop(6)
print("The array after 5 value poped ", a)
a.remove(8)
print("The array after removed value 4", a)
a.reverse()
print("The array after reverse function  ",a)
lst=a.tolist()
print("The array converted to list  ",lst)



4.   Write a program to sort the array elements

from array import *
x=array('i',[])
n=int(input("Enter the size of array"))
for i in range(n):
    x.append(int(input("Enter element")))
for i in range(n):
    print(x[i])
#print(x)
 for i in range(n):
        j=i+1
        for j in range(n):
             if a[i]>a[j]:
                t=a[i]
               a[i]=a[j]
               a[j]=t

print("After sorting",a)              


5.    Create a program to search the position of an element in an array using index() method of array class.


from array import *
x=array('i',[])
n=int(input("Enter the size of array"))

for i in range(n):
    x.append(int(input("Enter element")))
 
for i in range(n):
    print(x[i])
ind=int(input("Enter element"))
try:
     pos=x.index(ind)
     print("Element found at  ",pos)
except ValueError:
    print("Element not found")