An array is basically a data structure which can hold one value at a time. It is a collection or ordered series of elements of the same type.
Many of us gets confused whether list and arrays are the same or not.
Lists vs. arrays
- Arrays and lists have the same way of storing data.
- Arrays take only a single data type elements but lists can have any type of data.
- Other than a few operations, the kind of operations performed on them are different.
Array in python can be created after importing the array module.
e.g.,import arrayarr=array.array(‘i’, [1,2,3])print(arr)
Basic operations on array:-
- Finding the length of array- Length of an array is the number of elements that are actually present in an array. We can use the function len() to achieve it.
import array a=arr.array('i', [a1, a2, a3]) len(a)
- Adding/ changing an element- Functions used to add element to an array are append(), insert() and extend().
import array a=array.array('i', [1,2,3]) a.append(5) print(a) a.extend([4,5,6]) print(a) a.insert(2, 7) print(a)
- Removing an element- Functions used to remove or delete an element of an array are pop() and remove()
import array a=array.array('i', [1,2,3,4,5,6,7]) print(a.pop(2)) a.remove(7) print(a)
This is all about initializing an array in python.