Arrays
Module 2
NumPy Tutorial
• NumPy is a Python library.
• NumPy is used for working with arrays.
• NumPy is short for "Numerical Python".
• NumPy was created in 2005 by Travis
Oliphant.
• It is an open source project
Why Use NumPy?
• In Python we have lists that serve the purpose of
arrays, but they are slow to process.
• NumPy aims to provide an array object that is up
to 50x faster than traditional Python lists.
• The array object in NumPy is called ndarray, it
provides a lot of supporting functions that make
working with ndarray very easy.
• Arrays are very frequently used in data science,
where speed and resources are very important.
Why is NumPy Faster Than Lists?
• NumPy arrays are stored at one continuous
place in memory unlike lists, so processes can
access and manipulate them very efficiently.
• This behavior is called locality of reference in
computer science.
• This is the main reason why NumPy is faster
than lists. Also it is optimized to work with
latest CPU architectures.
• Once NumPy is installed, import it in your
applications by adding the import keyword:
• import numpy
• Or
• import numpy as np
Code Example
• import numpy
• a = [Link]([1, 2, 3, 4, 5])
• print(a)
• Output
• [1 2 3 4 5]
NumPy as np
• NumPy is usually imported under the np alias.
• alias: In Python alias are an alternate name for
referring to the same thing.
• import numpy as np
• Now the NumPy package can be referred to as
np instead of numpy.
Introduction to Arrays
• An array is a collection of elements stored at
contiguous memory locations.
• It allows random access to elements using
indices.
• Arrays are widely used in data storage and
manipulation.
Characteristics of Arrays
• Fixed size – size must be defined at creation.
• Homogeneous elements – all elements are of
same data type.
• Efficient indexing – constant time access using
indices.
Applications of Arrays
• Storing large collections of data.
• Used in searching and sorting algorithms.
• Matrix representation in scientific computing.
• Basis for advanced data structures like heaps
and hash tables.
1D Array Representation
Arrays
• NumPy is used to work with arrays. The array
object in NumPy is called ndarray.
• We can create a NumPy ndarray object by
using the array() function.
Code Example
• #Example
• import numpy as np
• arr = [Link]([1, 2, 3, 4, 5])
• print(arr)
• Output
• [1 2 3 4 5]
Code Example
• #Example
• import numpy as np
• arr = [Link]([1, 2, 3, 4, 5])
• print(arr)
• print(type(arr))
• Output
• [1 2 3 4 5]
• <class '[Link]'>
Dimensions in Arrays
• A dimension in arrays is one level of array
• 0-D Arrays
• 0-D arrays, or Scalars, are the elements in an
array.
• Each value in an array is a 0-D array.
Code Example
• #Example - Create a 0-D array with value 42
• arr = [Link](42)
• print(arr)
• Output
• 42
1-D Arrays
• An array that has 0-D arrays as its elements is
called uni-dimensional or 1-D array.
• These are the most common and basic arrays.
Code Example
• # Example - Create a 1-D array containing the
values 1,2,3,4,5:
• import numpy as np
• arr = [Link]([10,5,6,2,8])
• print(arr)
• Output
• [10 5 6 2 8]
2-D Arrays
• An array that has 1-D arrays as its elements is
called a 2-D array.
• These are often used to represent matrix
2D Array Representation
Code Example
• Create a 2-D array containing two arrays with the
values 1,2,3 and 4,5,6:
• import numpy as np
• arr = [Link]([[1, 2, 3], [4, 5, 6]])
• print(arr)
• Output
[[1 2 3]
[4 5 6]]
3-D arrays
• An array that has 2-D arrays (matrices) as its
elements is called 3-D array.
Code Example – 3D Arrays
• import numpy as np
• arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
• print(arr)
Output
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
Check Number of Dimensions?
• NumPy Arrays provides the ndim attribute
that returns an integer that tells us how many
dimensions the array have.
• Example
• Check how many dimensions the arrays have:
Code Example
• a = [Link](42)
• b = [Link]([1, 2, 3, 4, 5])
• c = [Link]([[1, 2, 3], [4, 5, 6]])
• print('dimension of a is',[Link])
• print('dimension of b is',[Link])
• print('dimension of c is',[Link])
• Output
• dimension of a is 0
• dimension of b is 1
• dimension of c is 2
Array Operations
• NumPy Array Indexing - Access Array Elements
• Array indexing is the same as accessing an
array element. You can access an array
element by referring to its index number.
• The indexes in NumPy arrays start with 0,
meaning that the first element has index 0,
and the second has index 1 etc.
Code Example
• arr = [Link]([1, 2, 3, 4])
• print(arr[2])
• Output
• 3
Code Example
• #Example - Get the second element from the
following array.
• import numpy as np
• arr = [Link]([1, 2, 3, 4])
• print(arr[1])
• Output
• 2
Code Example
• #Example - Get third and fourth elements
from the following array and add them.
• import numpy as np
• arr = [Link]([1, 2, 3, 4])
• print(arr[2] + arr[3])
• Output
• 7
Accessing 2-D Arrays
• To access elements from 2-D arrays, we can
use comma separated integers representing
the dimension and the index of the element.
Code Example
• import numpy as np
• a = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
• print(a)
• print('3rd element on second row: ', a[1, 2])
Output
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
3rd element on second row: 8
Code Example
• #Example - Access the element on the 2nd
row, 5th column:
• import numpy as np
• arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
• print('5th element on 2nd row: ', arr[1, 4])
• Output
• 5th element on 2nd row: 10
Negative Indexing
• Use negative indexing to access an array from
the end.
Code Example
• import numpy as np
• a = [Link]([1, 2, 3, 4])
• print(a[-2] )
• Output
• 3
Code Example
• #Example - Print the last element from the 2nd
dim:
• import numpy as np
• arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
• print('Last element from 2nd dim: ', arr[1, -1])
• Output
• Last element from 2nd dim: 10
Slicing arrays
• Slicing in python means taking elements from
one given index to another given index.
• We pass slice instead of index like this:
[start:end].
• We can also define the step, like this:
[start:end:step].
• If we don't pass start its considered 0
• If we don't pass end its considered length of array
in that dimension
• If we don't pass step its considered 1
Code Example
• a = [Link]([1, 2, 3, 4, 5, 6, 7])
• print(a[1:4])
• Output
• [2 3 4]
• #Note: The result includes the start index, but
excludes the end index
Code Example
• #Example - Slice elements from index 4 to the
end of the array:
• import numpy as np
• arr = [Link]([1, 2, 3, 4, 5, 6, 7])
• print(arr[2:])
• Output
• [3 4 5 6 7]
Code Example
• #Example - Slice elements from the beginning
to index 4 (not included):
• import numpy as np
• arr = [Link]([1, 2, 3, 4, 5, 6, 7])
• print(arr[:5])
• Output
• [1 2 3 4 5]
Negative Slicing
• Use the minus operator to refer to an index
from the end:
• Example
• Slice from the index 3 from the end to index 1
from the end:
Code Example
• import numpy as np
• arr = [Link]([1, 2, 3, 4, 5, 6, 7])
• print(arr[-3:-1])
• Output
• [5 6]
STEP
• Use the step value to determine the step of
the slicing:
• Example
• Return every other/alternate element from
index 1 to index 5:
Code Example
• import numpy as np
• arr = [Link]([1, 2, 3, 4, 5, 6, 7])
• print(arr[1:5:2])
• Output
• [2 4]
Code Example
• import numpy as np
• arr = [Link]([1, 2, 3, 4, 5, 6, 7])
• print(arr[::2])
• Output
• [1 3 5 7]
Slicing 2-D Arrays
• Example
• From the second element, slice elements from
index 1 to index 4 (not included):
Code Example
• import numpy as np
• arr = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
• print(arr[0, 1:4])
• Output
• [2 3 4]
Code Example
• #Example - From both elements, return index 2:
• import numpy as np
• arr = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
• print(arr[0:2, 2])
• Output
• [3 8]
Code Example
• #Example - From both elements, slice index 1 to
index 4 (not included), this will return a 2-D array:
• import numpy as np
• arr = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
• print(arr[0:2, 1:4])
• Output
• [[2 3 4]
• [7 8 9]]
Checking the Data Type of an Array
• The NumPy array object has a property called
dtype that returns the data type of the array:
• Example
• Get the data type of an array object:
Code Example
• import numpy as np
• arr = [Link]([1, 2, 3, 4])
• print([Link])
• Output
• int64
• import numpy as np
• arr = [Link]([1.4, 2.0, 3.5, 4.9])
• print([Link])
• Output
• float64
Shape of an Array
• The shape of an array is the number of
elements in each dimension. ie; it returns
number of rows and columns for a 2D array
• NumPy arrays have an attribute called shape
that returns a tuple with each index having
the number of corresponding elements.
• #Example - Print the shape of a 2-D array:
• import numpy as np
• arr = [Link]([[1, 2, 3], [5, 6, 7], [10,11,12]])
• print(arr)
• print('shape is',[Link])
• Output
• [[ 1 2 3]
• [ 5 6 7]
• [10 11 12]]
• shape is (3, 3)
• import numpy as np
• arr = [Link]([1, 2, 3, 4])
• print([Link])
• Output
• (4,)
Reshaping arrays
• Reshaping means changing the shape of an array.
• The shape of an array is the number of elements in each
dimension.
• By reshaping we can add or remove dimensions or change
number of elements in each dimension.
• Reshape From 1-D to 2-D
• Example
• Convert the following 1-D array with 12 elements into a 2-D
array.
• The outermost dimension will have 4 arrays, each with 3
elements:
• import numpy as np
• arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
• print('old array is', arr)
• newarr = [Link](3,4)
• print('new array is', newarr)
Output
old array is [ 1 2 3 4 5 6 7 8 9 10 11 12]
new array is [[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Can We Reshape Into any Shape?
• Yes, as long as the elements required for
reshaping are equal in both shapes.
• We can reshape an 8 elements 1D array into 4
elements in 2 rows 2D array but we cannot
reshape it into a 3 elements 3 rows 2D array as
that would require 3x3 = 9 elements.
• Example
• Try converting 1D array with 8 elements to a 2D
array with 3 elements in each dimension (will
raise an error):
• import numpy as np
• arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8])
• newarr = [Link](3, 4)
• print(newarr)
• ValueError: cannot reshape array of size 8 into
shape (3,4)
Iterating Arrays
• Iterating means going through elements one by
one.
• As we deal with multi-dimensional arrays in
numpy, we can do this using basic for loop of
python.
• If we iterate on a 1-D array it will go through each
element one by one.
• Example
• Iterate on the elements of the following 1-D
array:
import numpy as np
arr = [Link]([1, 2, 3, 10,17,19])
for y in arr:
print(y)
Output
1
2
3
10
17
19
Joining NumPy Arrays
• Joining means putting contents of two or
more arrays in a single array.
• We pass a sequence of arrays that we want to
join to the concatenate() function, along with
the axis. If axis is not explicitly passed, it is
taken as 0.
• Example
• Join two arrays
• import numpy as np
• arr1 = [Link]([1, 2, 3])
• arr2 = [Link]([4, 5, 6])
• arr = [Link]((arr1, arr2))
• print(arr)
• Output
• [1 2 3 4 5 6]
Sorting Arrays
• Sorting means putting elements in an ordered
sequence.
• Ordered sequence is any sequence that has an
order corresponding to elements, like numeric
or alphabetical, ascending or descending.
• The NumPy ndarray object has a function
called sort(), that will sort a specified array.
• Note: This method returns a copy of the array,
leaving the original array unchanged.
• #Example Sort the array:
• import numpy as np
• arr = [Link]([3, 2, 0, 1])
• arr1 = [Link](arr)
• print([Link](arr))
• print('sorted array is', arr1)
• print('original array', arr)
• Output
• [0 1 2 3]
• sorted array is [0 1 2 3]
• original array [3 2 0 1]
Sorting a 2-D Array
• If you use the sort() method on a 2-D array,
both arrays will be sorted:
• Example
• Sort a 2-D array:
• import numpy as np
• arr = [Link]([[3, 2, 4], [5, 0, 1]])
• print([Link](arr))
• Output
• [[2 3 4]
• [0 1 5]]
Another way to create Arrays
• using [Link]() function to create arrays
• The arange() function in NumPy returns an array with evenly spaced
valueswithin a given range.
• It’s similar to Python’s built-in `range()`, but returns a NumPy array
instead of a list.
• import numpy as np
• x = [Link](10)
• print(x)
• Output
• [0 1 2 3 4 5 6 7 8 9]
Syntax
• [Link]([start], stop, [step], dtype=None)
• start (optional) → The starting value (default = 0).
• stop → The end value (not included).
• step (optional) → The difference between values
(default = 1).
• dtype (optional) → The type of output array (e.g.,
int, float).
Example
• import numpy as np
• x = [Link](1,10)
• print(x)
• Output
• [1 2 3 4 5 6 7 8 9]
Example
• import numpy as np
• x = [Link](1,10,2)
• print(x)
• Output
• [1 3 5 7 9]
• arr = [Link](0, 1, 0.2)
• print(arr)
• Output
• [0. 0.2 0.4 0.6 0.8]
• import numpy as np
• a = [Link](12).reshape(3, 4)
• print(a)
Output
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
• print([Link]) # (3,4)
• print([Link]) #2
• a = [Link]( [20,30,40,50] )
• print(a)
• b = [Link]( 4 )
• print(b)
• c = a-b
• print(c)
Output
[20 30 40 50]
[0 1 2 3]
[20 29 38 47]
2D array Operations
A = [Link]([[1,1],
[0,1]] )
B = [Link]( [[2,0],
[3,4]] )
print(A*B) # Element wise product
Output
[[2 0]
[0 4]]
Creating zero matrix
• import numpy as np
• # 3x3 Zero Matrix
• Z = [Link]((3, 3))
• print(Z)
• Output
• [[0. 0. 0.]
• [0. 0. 0.]
• [0. 0. 0.]]
Creating Identity Matrix
• # 3x3 Identity Matrix
• I = [Link](3)
• print(I)
• Output
• [[1. 0. 0.]
• [0. 1. 0.]
• [0. 0. 1.]]
Identity matrix
• I2 = [Link](4) # 4x4 Identity Matrix
• print(I2)
• Output
• [[1. 0. 0.]
• [0. 1. 0.]
• [0. 0. 1.]]
Ones matrix – all elements are 1
• import numpy as np
• # 3x3 Ones Matrix
• O = [Link]((3, 3))
• print(O)
• Output
• [[1. 1. 1.]
• [1. 1. 1.]
• [1. 1. 1.]]
• O_int = [Link]((3, 3), dtype=int)
• print(O_int)
• Output
• [[1 1 1]
• [1 1 1]
• [1 1 1]]
Summary
• [Link]((m, n))→ Zero Matrix
• [Link]((m, n)) → Ones Matrix
• [Link](n) or [Link](n) → Unit (Identity)
Matrix
Dot product of 1D array
• The dot product of two 1D arrays (vectors) is the sum of the products of
corresponding elements.
import numpy as np
# Define two 1D arrays
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
# Compute dot product
dot_product = [Link](a, b)
print("Array A:", a)
print("Array B:", b)
print("Dot Product:", dot_product)
Output
Array A: [1 2 3]
Array B: [4 5 6]
Dot Product: 32
Dot product of 2D arrays
When both inputs are 2D arrays, the `dot()` function performs matrix multiplication(not
element-wise multiplication).
First method using [Link]
Output
Matrix A:
import numpy as np
[[1 2]
# Define two 2D arrays
[3 4]]
A = [Link]([[1, 2],
[3, 4]])
Matrix B:
B = [Link]([[5, 6],
[[5 6]
[7, 8]])
[7 8]]
# Compute dot product (matrix multiplication)
dot_product = [Link](A, B)
Dot Product (A · B):
[[19 22]
print("Matrix A:\n", A)
[43 50]]
print("Matrix B:\n", B)
print("Dot Product (A · B):\n", dot_product)
Dot product of 2D arrays
When both inputs are 2D arrays, the `dot()` function performs matrix multiplication(not
element-wise multiplication).
Second method
Output
Matrix A:
import numpy as np
[[1 2]
# Define two 2D arrays
[3 4]]
A = [Link]([[1, 2],
[3, 4]])
Matrix B:
B = [Link]([[5, 6],
[[5 6]
[7, 8]])
[7 8]]
# Compute dot product (matrix multiplication)
dot_product = [Link](B)
Dot Product (A · B):
[[19 22]
print("Matrix A:\n", A)
[43 50]]
print("Matrix B:\n", B)
print("Dot Product (A · B):\n", dot_product)
Difference between [Link]() and .dot()
• [Link]() -- This is a function in the NumPy module.
• You call it directly using `[Link](x, y)`.
• It works on any array-like objects (lists, tuples, arrays).
• .dot() -- This is an array method, available for NumPy
ndarray objects.
• You call it using `[Link](other_array)`.
• It is essentially the same as `[Link]()` but works only
on NumPy arrays.
Sum of two arrays
A = [Link]([[1,1],
[0,1]] )
B = [Link]( [[2,0],
[3,4]] )
print(A+B)
Output
[[3 1]
[3 5]]
Array Methods
Python has a set of built-in methods that you can use on
lists/arrays.
Method Description
• append() Adds an element at the end of the list
• clear() Removes all the elements from the list
• copy() Returns a copy of the list
• count() Returns the number of elements with the
specified value
• extend() Add the elements of a list (or any iterable), to
the end of the current list
• index() Returns the index of the first element with the
specified value
• insert() Adds an element at the specified position
• pop() Removes the element at the specified position
• remove() Removes the first item with the specified value
• reverse() Reverses the order of the list
• sort() Sorts the list
Using Numpy module write menu driven program to do
following
a) Create an array filled with 1’s.
b) Find maximum and minimum values from an
array
c) Dot product of 2 arrays.
d) Reshape a 1-D array to 2-D array.
import numpy as np
def Array_Operations():
while True:
print("\n===== NumPy Menu =====")
print("1. Create an array filled with 1's")
print("2. Find maximum and minimum from an array")
print("3. Dot product of two arrays")
print("4. Reshape a 1-D array to 2-D array")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
arr = [Link]((rows, cols), dtype=int)
print("Array filled with 1's:\n", arr)
elif choice == '2':
elements = input("Enter elements of the array: ")
arr = [Link](list(map(int, [Link]())))
print("Array:", arr)
print("Maximum value:", [Link](arr))
print("Minimum value:", [Link](arr))
elif choice == '3':
a = [Link](list(map(int, input("Enter first array : ").split())))
b = [Link](list(map(int, input("Enter second array: ").split())))
if [Link] == [Link]:
print("Dot product:", [Link](a, b))
else:
print("Error: Arrays must be of the same shape for dot product.")
elif choice == '4':
arr = [Link](list(map(int, input("Enter 1-D array elements: ").split())))
rows = int(input("Enter number of rows for reshaping: "))
cols = int(input("Enter number of columns for reshaping: "))
if rows * cols == [Link]:
reshaped = [Link]((rows, cols))
print("Reshaped array:\n", reshaped)
else:
print("Error: Cannot reshape array with given dimensions.")
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
# main program
Array_Operations()
Write a Python program to calculate
area of a circle using math
import math
radius = float(input("Enter the radius of the circle: "))
# Formula: Area = π * r²
area = [Link] * [Link](radius, 2)
print(f"The area of the circle with radius {radius} is: {area}")
• Write the function used to generate an array of
numbers from 1 to 8.
# Generate array of numbers from 1 to 8
import numpy as np
numbers = [Link](1,9)
print(numbers)
Output
[ 1 2 3 4 5 6 7 8]
• Write a Python code using NumPy to generate
an array of even numbers between 2 and 10
import numpy as np
# Generate even numbers between 2 and 10
even_numbers = [Link](2, 11, 2)
print("Even numbers between 2 and 10:",
even_numbers)
Output
Even numbers between 2 and 10: [ 2 4 6 8 10]
• Write a python code to compute the square root of
each element in [9,16,25] using Numpy.
import numpy as np
arr = [Link]([9, 16,25])
# Compute square root of each element
sqrt_values = [Link](arr)
print("Square root of each element:", sqrt_values)
Output
Square root of each element: [3. 4. 5.]
Here, `[Link]()` applies the square root operation
element-wise on the NumPy array.
• Write a python code to generate an array of zeros
with size 4 using numpy.
import numpy as np
# Generate an array of zeros with size 4
zeros_array = [Link](4)
print("Array of zeros:", zeros_array)
Output
Array of zeros: [0. 0. 0. 0.]
• Write a python code to generate square matrix of
zeros with size 4 using numpy.
import numpy as np
# Generate a 4x4 square matrix of zeros
zeros_matrix = [Link]((4, 4))
print("4x4 Matrix of zeros:\n", zeros_matrix)
Output
4x4 Matrix of zeros:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
• Write a Python program using math functions to find the
area and circumference of a circle of radius 5.
import math
radius = 5
area = [Link] * [Link](radius, 2)
circumference = 2 * [Link] * radius
print(f"Radius: {radius}")
print(f"Area of the circle: {area:.2f}")
print(f"Circumference of the circle: {circumference:.2f}")
Output
Radius: 5
Area of the circle: 78.54
Circumference of the circle: 31.42
• Write a program to create a numpy array of integers from 1
to 15 and reshape it into a 3X 5 matrix.
import numpy as np
# Create array of integers from 1 to 15
arr = [Link](1, 16)
# Reshape into 3x5 matrix
matrix = [Link](3, 5)
print("Original Array:\n", arr)
print("\n3x5 Matrix:\n", matrix)
Output
Original Array: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
3x5 Matrix:
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]]
• Write a program to find the dot product of two arrays.
import numpy as np
# Define two arrays
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
# Compute dot product
dot_product = [Link](a, b)
print("Array A:", a)
print("Array B:", b)
print("Dot Product:", dot_product)
Output
Array A: [1 2 3]
Array B: [4 5 6]
Dot Product: 32