Python - Array

An array is a grid of elements that can be indexed. The elements are all of the same type, referred as array dtype. In Python, Arrays are dynamic, means we do not need to specify its size while declaring, it can shrink and grow at runtime. An array can be indexed by a tuple of nonnegative integers.

Example 1: Declare array of integer values and dispaly.

from array import *
nums = array('i',[10,20,30])
for i in nums:
    print(i)
10
20
30

Python - Type code

Type Code Data type Size(Byte) Range
b signed byte 1 -128 to 127
B unsigned byte 1 0 to 255
h signed short 2 -32768 to 32767
H unsigned short 2 0 to 65536
i signed int 2 -32768 to 32767
I unsigned int 2 0 to 65536
l signed long 4 -231 to 231-1
L unsigned long 4 0 to 232-1
f float 4 1.2e-38 to 3.4d+38
d double 8 2.3e-308 to 1.7e+308
u unicode(character) 2 Depend on number of characters

Python - Array functions

Example 2: Reverse the array.

from array import *
nums = array('i',[10,20,5,15])
nums.reverse()
for i in nums:
    print(i)

Example 3: Sort the array values

from array import *
nums=array('i',[10, 5, 20, 15, 1])
for i in range(0,len(nums)-1):
    for j in range(0,len(nums)-i-1):
        if nums[j]>nums[j+1]:
            nums[j+1],nums[j]=nums[j],nums[j+1]
print(nums)

Array - Input value from user

Example 4: Input number from user and store in array.

from array import *
arr = array('i',[])
n=int(input("Enter length of array"))
for i in range(n):
    x=int(input("Enter number"))
    arr.append(x)
print(arr)

Example 5: Input number and search in array.

from array import *
k=0
arr = array('i',[10,20,30,40,50])
n=int(input("Enter number to search:"))
for i in arr:
    k+=1
    if n==i:
        print("Found at",k,"position")
        break
else:
    print("Not Found")

Arrays using NumPy

NumPy (Numerical Python) is a open source Python library, which you have to install using pip command. NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices)

The latest version of NumPY is Version: 1.23, to install numpy type the following command:

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip install numpy

Example 6: Declare array using numpy

#from numpy import * #import NumPy
import numpy as np #another way to import NumPy

arr = array([1,2,3],int)
arr = array([1,2,3])
print(arr)

Example 7: NumPy Function zeros: Return a new array of given shape and type, filled with zeros.

from numpy import *

arr=zeros(5) #array([0., 0., 0., 0., 0.])
arr=zeros(5, int) #array([0, 0, 0, 0, 0]) with data type
arr=zeros((2,1)) #shape of array 2 rows and 1 column
arr=zeros((2,1),int) #2 rows and 1 column with dtype

s = (2,2)
arr=zeros(s) #define shape in variable

Example 8: NumPy Function ones: Return a new array of given shape and type, filled with ones.

from numpy import *

arr=ones(5) #array([1., 1., 1., 1., 1.])
arr=ones(5, int) #array([1, 1, 1, 1, 1]) with data type
arr=ones((2,1)) #shape of array 2 rows and 1 column
arr=ones((2,1),int) #2 rows and 1 column with dtype

s = (2,2)
arr=ones(s) #define shape in variable

Example 9: NumPy Function linspace: Return evenly spaced numbers over a specified interval.

from numpy import *

arr = linspace(2,20,10) #array([ 2.,  4.,  6.,  8., 10., 12., 14., 16., 18., 20.])
arr = linspace(2, 20, 10, dtype=int) #array([ 2,  4,  6,  8, 10, 12, 14, 16, 18, 20])
arr = linspace(2, 20, 10, endpoint=False, dtype=int) #array([ 2,  3,  5,  7,  9, 11, 12, 14, 16, 18])
arr = linspace(2, 20, 10, endpoint=False, dtype=int, retstep=True) #(array([ 2,  3,  5,  7,  9, 11, 12, 14, 16, 18]), 1.8)

Example 10: NumPy Functions.

from numpy import *
arr=arange(1,15,2)
print(arr)

arr = array([10,20,30,40])
arr = arr+5
print(arr)

arr1 = array([1,2,3,4,5])
arr2 = array([10,20,30,40,50])
arr3=arr1+arr2
print(arr3)

arr = array([10,200,30,40,50])
print(sin(arr))
print(cos(arr))
print(tan(arr))

print(sqrt(arr))
print(sum(arr))
print(min(arr))
print(max(arr))
print(sort(arr))

arr1 = array([1,2,3,4,5])
arr2 = arr1 #shallow copy
arr2 = arr1.copy() #deep copy
arr1[1]=20
print(arr1)
print(arr2)

#2 types of copy: shallow copy(default) and deep copy
#In deep copy change in one array doesnot reflect another.

Difference between Python list and NumPy array?

NumPy gives you an enormous range of fast and efficient ways of creating arrays and manipulating numerical data inside them. While a Python list can contain different data types within a single list, all of the elements in a NumPy array should be homogeneous. The mathematical operations that are meant to be performed on arrays would be extremely inefficient if the arrays weren't homogeneous.

NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types.

Array - 2 Dimensional

Example 11: Declare and display 2D-Array using numpy

from numpy import *

arr = array([[1,2,3], [4,5,6], [7,8,9]])
for i in arr:
    for j in i:
        print(j, end=' ')
    print()
1   2   3
4   5   6
7   8   9

Example 12: NumPy contain function that can be performed on 2D-Array.

from numpy import *

arr=array([[1,2,3],[4,5,6]])

print(arr)
print(arr.dtype) #data type
print(arr.ndim) #no of dimension
print(arr.shape) #no of rows, cols
print(arr.size) #no of elements
print(diagonal(arr)) #display diagonal elements
print(arr.min()) #display smallest element
print(arr.max()) #display largest element
print(ceil(arr)) #round 1 number up all array elements
print(floor(arr)) #round 1 number up all array elements
print(rint(arr)) #round 1 number up all array elements

arr2=array([[10,20,30],[40,50,60]])
arr3=arr+arr2 #sum of 2 matrix, shape should be same

Exercise: Python 2D-Array