Python Arrays
There is a problem with lists, its violets are the basic property of an array which is a homogeneous collection of elements.
Though there is no in-built support for arrays in python, we can use a module name array to create an array data structure.
Image credits to https://www.analyticsvidhya.com/
Syntax to create an array in Python using array Module:
import array
variable_name = array.array('Type code',[item1 , item2, item3,])
Example:
import array
arr = array.array('d', [1,2,3,4])
Python Array Type codes:
The Unicode decide the data type of all the elements and all the element data type should match the type code.
Syntax:
array.array(‘Type code or UniCode’ , [list of items] )
With the array module, we can only create an array of numeric elements.
In general, we use python lists as arrays, but theoretically, arrays cannot store different data types at once.
Python List
python_list = [1,2,3,4,5,"This is a List"]
print(python_list)
Array Module in Python
import array
python_array = array.array('i' , [1,2,4,5,6,7,])
print(python_array)
Access Array Elements
Like a List, the array uses indexing too, with sq. brackets [ ].
Example:
import array
arr = array.array ('i' , [1,3,4,6,7,10,11])
print("Element at Index 0:", arr[0])
print("Element at Index 1:", arr[1])
print("Element at Index 2:", arr[2])
Output:
Element at Index 0: 1
Element at Index 1: 3
Element at Index 2: 4
Add Elements to the Array:
We can either use the append or extend the method to add new elements to the array.
Example:
import array
my_arr = array.array('i', [1,2,3,4,5,6,7,8,9,10])
my_arr.append(100)
my_arr.extend([200,300,400])
print(my_arr)
Output:
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 200, 300, 400])
Delete Element from an Array:
To delete an element from an array we have 1 keyword del and 2 methods remove(value) and pop(index).
Example:
import array
my_arr = array.array('i', [1,2,3,4,5,6,7,8,9,10])
my_arr.pop(0) # delete the element at 0 index
my_arr.remove(10) # delete the value 10
del my_arr[2] # delete the my_arr[2] value
print(my_arr)
Conclusion:
We do not use a python array module to build arrays because we cannot perform a mathematical or arithmetic operation on array elements.