Python has a set of built-in methods that you can use on lists/arrays.
- append()
Adds an element at the end of the array/list
import array as ar
a= ar.array('i',[1,2,3,5])
a.append(7)
print(a)
#output: array('i',[1,2,3,5,7])
- insert(pos, value)
Inserts an element at desired position of the array
import array
a= array('i',[1,2,3,5])
a.insert(1,7)
print(a)
#output: array('i',[1,7,2,3,5])
- remove(value)
To remove an element from the array.
import array
a= array('i',[1,2,3,5])
a.remove(3)
print(a)
#output: array('i',1,2,5])
- extend(arr)
Adding another array to a existing array using extend method
import array
a= array('i',[1,2,3,5])
a.extend([33,55])
print(a)
#output: array('i',[1,2,3,5,33,55])
- pop()
Pop method removes the last element in array
import array
a= array('i',[1,2,3,5])
a.pop()
print(a)
#output: array('i',[1,2,3])
- index(value)
To know the index of a value in an array using index(val) method.
import array
a= array('i',[1,2,3,5])
print(a.index(3))
#output: 2
- reverse()
To reverse an array use reverse() method
import array
a= array('i',[1,2,3,5])
a.reverse()
print(a)
#output: array('i',[5,3,2,1])
- fromlist(list)
fromlist() is used to add a list to the end of the array. It will take a list as its input argument and the output of this function is an array with list appended at the end of the array.
import array
a= array('i',[1,2,3,5])
a.fromlist([10,7,3])
print(a)
#output: array('i',[1,2,3,5,10,7,3])
- count(val)
count() will tell the total number of occurrences of the given value in the array.
import array
a= array('i',[1,2,3,3,3,3,5])
print(a.count(3))
#output: 4
Top comments (0)