Module 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

Module-4

Creating, Accessing and Manipulating Lists, Sets, Tuples and


Dictionaries, Understanding the differences among them,
Applications of the Data Structures. Using Branching and Control
loops with Data structures, Matrix Operations using Numpy.

06-07-2024 Dr. V.Srilakshmi 1


Data structures
• Data structures are a way of organizing and storing data so
that they can be accessed and worked with efficiently.
Data Types in Python

• Numbers
• Booleans
• Strings
• List
• Tuple
• Set
• Dictionary
List

• Lists in Python are used to store collection of heterogeneous items.


• Lists are used to store multiple items in a single variable.
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item has index [1] etc.

Ex:
• list1 = ['physics', 'chemistry', 1997, 2000];
• list2 = [1, 2, 3, 4, 5 ];
How to create a list?

• In Python programming, a list is created by placing all the items (elements)


inside a square bracket [ ], separated by commas.
• It can have any number of items and they may be of different types
(integer, float, string etc.).

• list my_list = []
• my_list = [1, 2, 3]
• my_list = [1, "Hello", 3.4]
• Also, a list can even have another list as an item. This is called nested list.
• my_list = ["mouse", [8, 4, 6], ['a']]
How to access elements from a list?
• List items are indexed and you can access them by referring to the index number
• We can use the index operator [] to access an item in a list.
• Index starts from 0. So, a list having 5 elements will have index from 0 to 4.
• Trying to access an element out of range index then it will raise an IndexError.
• The index must be an integer. We can't use float or other types, this will result
into TypeError.

Negative indexing
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second
last item and so on.
How to access elements from a list?

thislist = ["apple", "banana", "cherry"]


print(thislist[1]) banana

thislist = ["apple", "banana", "cherry"]


print(thislist[-1]) cherry

Range of Indexes
• You can specify a range of indexes by specifying where to start and where to end the
range.
• When specifying a range, the return value will be a new list with the specified items.

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon"]


print(thislist[2:5])
['cherry', 'orange', 'kiwi']
How to access elements from a list?

thislist =["apple", "banana", "cherry", "orange", "kiwi"]


print(thislist[:3])
['apple', 'banana', 'cherry’,]

thislist = ["apple", "banana", "cherry", "orange", "kiwi"]


print(thislist[2:])
['cherry', 'orange', 'kiwi']

thislist = ["apple", "banana", "cherry", "orange", "kiwi"]


print(thislist[-4:-1])
['banana', 'cherry', 'orange']
Change List Items
• To change the value of a specific item, refer to the index number:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant"
['apple', 'blackcurrant', 'cherry']
print(thislist)

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
Add List Items
Append Items:
• To add an item to the end of the list, use the append() method:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)
['apple', 'banana', 'cherry', 'orange']

Insert Items:
• The insert() method inserts an item at the specified index:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist) ['apple', 'orange', 'banana', 'cherry']
Remove List Items
Remove Specified Item:
• The remove() method removes the specified item.
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
['apple', 'cherry']
• If there are more than one item with the specified value, the remove() method removes the first
occurrence:
Remove Specified Index:
• The pop() method removes the element at specified index.

thislist = ["apple", "banana", "cherry"]


thislist.pop(0)
print(thislist) ['banana', 'cherry’]

• If you do not specify the index, the pop() method removes the last item.

thislist = ["apple", "banana", "cherry"]


thislist.pop()
print(thislist) ['apple', 'banana']
Loop Through a List
You can loop through the list items by using a for loop

thislist = ["apple", "banana", "cherry"] apple


for x in thislist: banana
print(x) cherry

Loop Through the Index Numbers:


• You can also loop through the list items by referring to their index number.
• Use the range() and len() functions to create a suitable iterable.

Example: Print all items by referring to their index number:

list = ["apple", "banana", "cherry"] apple


n=len(list) banana
for i in range(n): cherry
print(list[i])
Practice program: Print all items, using a while loop
Given a list of numbers. write a program to turn every item of a list into its square.

Given: Expected output:


numbers = [1, 2, 3, 4, 5, 6, 7] [1, 4, 9, 16, 25, 36, 49]

Program:
numbers = [1, 2, 3, 4, 5, 6, 7]
res=[]
for i in numbers:
res.append(i*i)
print("Input:",numbers)
print("Output:",res) Input: [1, 2, 3, 4, 5, 6, 7]
Output: [1, 4, 9, 16, 25, 36, 49]
Methods Of list
animal = ['cat', 'dog', 'rabbit']
len(): It returns the number of elements in the list.
Print(len(animal))

extend():it adds all items of a one list to the end of another list.
syntax:
• list1.extend(list2)
• Here, the elements of list2 are added to the end of list1.

language = ['French', 'English', 'German']


language1 = ['Spanish', 'Portuguese']
language.extend(language1)
Output:
print('Language List: ', language) Language List: ['French', 'English', 'German', 'Spanish', 'Portuguese']
Methods Of list
count(): method returns the number of occurrences of an element in a list.
Syntax: list.count(element)

vowels = ["C","Python","java","Python"]
count = vowels.count('Python')
print(count) #2
Output:
2
sum() : Calculates sum of all the elements of List.
Syntax: sum(List)

List = [1, 2, 3, 4, 5]
print(sum(List))
Methods Of list

min() : Calculates minimum of all the elements of List.


Syntax: min(List)

List = [2, 4, 3, 5, 1, 2.5]


print(min(List)) #1

max(): Calculates maximum of all the elements of List.


Syntax: max(List)
List = [2, 4, 3, 5, 1, 2.5]
print(max(List)) #5.
Methods Of list
• sort() method can be used to sort List with Python in ascending or descending
order.

numbers = [1, 3, 4, 2]
strs = ["geeks", "code", "ide", "practice"]
strs.sort()
# Sorting list of Integers in ascending
print(strs)
print(numbers.sort())
print(numbers) # [1, 2, 3, 4]

#['code', 'geeks', 'ide', 'practice']

numbers = [1, 3, 4, 2]
numbers.sort(reverse=True)

print(numbers) # [4, 3, 2, 1]
Write a python program to read items from the user and display items in the list?

L=[]
n=int(input("enter size of list"))
i=0
while(i<n):
a=int(input())
L.append(a)
i=i+1
for j in L:
print(j)
Python program that search for a specific element in a list

list=[5,6,7,8,9]
num=int(input("enter element to search"))
for i in list:
if i==num:
print(num,"found in the list")
break
else:
print(num,"not found in the list")

enter element to search 8


8 found in the list

enter element to search 20


20 not found in the list
Write a python program to find the largest element in a list without using method

list=[1,2,4,7,3]
max=list[0]
for a in list:
if a > max:
max = a
print("largets is",max)
create a Python program to count the number of strings in a list that have a length of 3 or more and
where the first and last characters are the same

string_list = ["level", "python", "radar", "hh", "noon"]


count = 0

for word in string_list:


if len(word) >= 3 and word[0] == word[-1]:
count += 1
print("Count is:", count)
List Comprehension:

• List comprehension is an elegant and concise way to create new list from
an existing list in Python.
• List comprehension consists of an expression followed by for
statement inside square brackets.

pow2 = [2 ** x for x in range(10)]


print(pow2)
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
tuple

• A tuple is a collection of elements separated by commas.


• Tuple items are ordered, unchangeable, and allow duplicate values.
• Since tuple are unchangeable, iterating through tuple is faster than with list.
Creating a Tuple

• A tuple is created by placing all the items (elements) inside a parentheses


(), separated by comma.
• A tuple can have any number of items and they may be of different types
(integer, float, list, string etc.).

• my_tuple = ()
• my_tuple = (1, 2, 3)
• my_tuple = (1, "Hello", 3.4)
• my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
• my_tuple = 3, 4.6, "dog"
Accessing Elements in a Tuple

Indexing:
• We can use the index operator [] to access an item in a tuple where the
index starts from 0.
• The index must be an integer, so we cannot use float or other types. This
will result into TypeError
Negative Indexing
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second last item and so on.
Slicing
• We can access a range of items in a tuple by using the slicing operator -
colon ":".
Accessing Elements in a tuple
my_tuple = ('python','java','C','C++’)

print(my_tuple[3])
print(my_tuple[-2])
print(my_tuple[1:3])
print(my_tuple[:])

t=(1,2,3)
t[0] = 5

n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

print(n_tuple[1])
print(n_tuple[0][1])
print(n_tuple[2][2])
Basic tuple Operations
Methods
t=(1,4,5,3,8)
print(sum(t))
print(max(t))
print(min(t))

T=(1,5,3,2,5)
print(T. count(5)) # 2
Methods
tuple(): converts a list of items into tuples

L=[1,5,3]
T=tuple( L )
print(T)

Sorted():
p = ('e', 'a', 'u', 'o', 'i')
print(sorted(p)) ['a', 'e', 'i', 'o', 'u’]
print(sorted(p,reverse=True)) ['u', 'o', 'i', 'e', 'a']
Even and Odd sum in a tuple
t=(1,2,3,4,5)
sume=0
sumo=0
for i in t:
if(i%2==0):
sume=sume+i
else:
sumo=sumo+i
print(sume)
print(sumo)
python set
• A set is an unordered collection of items.
• All the elements in the set are unique.
• Sets can be used to perform mathematical set operations like union, intersection,
symmetric difference etc.
How to create a set:
• A set is created by placing all the elements inside curly braces {}, separated by
comma or by using the built-in function set().
• It can have any number of items and they may be of different types (integer, float,
tuple, string etc.).
my_set = {1, 2, 3}
my_set = set([1,2,3])
my_set = {1,2,3,4,3,2} # {1,2,3,4}
Access Items
• We cannot access or change an element of set using indexing or slicing.
• But you can loop through the set items using a for loop

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x) cherry
banana
apple
Join Two Sets or Python Set Operations
• The union() method that returns a new set containing all items from both sets
• The intersection() method will return a new set, that only contains the items that are present in
both sets.
• Difference of A and B (A - B) is a set of elements that are only in A but not in B
• The symmetric_difference() method will return a new set, that contains only the elements that
are NOT present in both sets.

Program:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

print(A.union(B)) #{1, 2, 3, 4, 5, 6, 7, 8}
print(A.intersection(B)) #{4, 5}
print(A.difference(B)) #{1, 2, 3}
print(A.symmetric_difference(B)) # {1, 2, 3, 6, 7, 8}
Python Set Methods
add() : It adds a given element to a set. If the element is already present, it
doesn't add any element.
v = {'a', 'e', 'i', 'u'}
v.add('o')
print('Vowels are:', v)

remove(): method searches for the given element in the set and removes it.
Ex:
language = {'English', 'French', German'}
language.remove('German')
print(language)
Output: {'English', 'French'}
Python Set Methods
numbers = [2.5, 3, 4, -5]
print(sum(numbers)) # 4.5
print(max(numbers)) #4
print(min(numbers)) # -5
print(len(numbers)) #4
print (sorted(numbers)) # [-5, 2.5, 3, 4]
Python Dictionaries
• Dictionaries are used to store data as key:value pairs.
• Dictionaries are written with curly brackets, and have keys and values
• A dictionary is a collection which is changeable and do not allow
duplicates.
• Dictionaries cannot have two items with the same key:
• The value can be accessed by unique key in the dictionary.
Ex:
my_dict = {1: 'apple', 2: 'ball'}
creating a dictionary
• Creating a dictionary is as simple as placing items inside curly
braces {} separated by comma.
• An item expressed as a key: value pair,

my_dict = {} #empty dictionary


my_dict = {1: 'apple', 2: 'ball’}

• using dict():
my_dict = dict({1:'apple', 2:'ball'})
Accessing elements from a dictionary
• You can access the items of a dictionary by referring to its key name,
inside square brackets
• By using get() method also you can access the elements of a
dictionary.

my_dict = {'name':'Jack', 'age': 26}


print(my_dict['name'] // Jack
print(my_dict.get('age')) //26
Adding or changing elements in a dictionary?
• We can add new items or change the value of existing items
using assignment operator.
• If the key is already present, value gets updated, else a new
key: value pair is added to the dictionary.
Ex:
my_dict = {'name':'Jack', 'age': 26}
my_dict['age'] = 27
my_dict['address'] = 'Downtown'
print(my_dict) # Output: {'address': 'Downtown', 'age': 27,
'name': 'Jack’}
Python Dictionary Methods
1. get()
2. pop()
3. del
4. clear()
5. Items()
6. update()
7. keys()
8. values()
9. copy()
pop():
• The pop() method removes and returns an element
from a dictionary having the given key.

Ex:
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
element = sales.pop('apple')
print('The popped element is:', element) #2
del:
• del keyword is used to remove individual items or the entire
dictionary itself.
Ex:
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
del squares[5]
print(squares)
del squares
clear():
• It is used to remove all the items at once.
squares.clear()
print(squares) # Output: {}
update()
• It is used to update or add elements to dictionary.
• The update() method adds element(s) to the dictionary if the key is
not in the dictionary.
• If the key is in the dictionary, it updates the key with the new value.
Ex:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
print(thisdict)
update()
• The items() method returns key-value pairs of the
dictionary, as tuples in a list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
keys() and values()
• The keys() method returns a list of all the keys in the dictionary
Syntax: dict.keys()
• The values() method returns a list of all the values in the
dictionary.
Syntax: dict.values()
Example:

sales = { 'apple': 2, 'orange': 3, 'grapes': 4}


print(sales.keys()) dict_keys(['apple', 'orange', 'grapes'])
print(sales.values()) dict_values([2, 3, 4])
copy()
• copy() method returns a shallow copy of the dictionary.
• It doesn't modify the original dictionary
syntax : dict.copy()
Ex:
original = {1:'one', 2:'two'}
new = original.copy()
print(new)
sorted()

Jersey={10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'}
print(sorted(jersey)) [5, 10, 18, 45]
print(sorted(jersey. Keys())) [5, 10, 18, 45]
print(sorted(jersey.values())) ['Dravid', 'Kohli', 'Rohith', 'sachin']
print(len(jersey)) #4
Loop Through a Dictionary
• for loop can be used to iterate though each key in a dictionary.
Ex:
10
jersey = {10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'} 5
for x in jersey: 45
print(x) 18

Print all values in the dictionary, one by one:


jersey= {10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'}
for x in jersey: sachin
Dravid
print(jersey[x]) Rohith
Kohli
Loop Through a Dictionary
• You can also use the values() method to return values of a
dictionary:
sachin
Dravid
Jersey={10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'} Rohith
Kohli
for x in jersey.values():
print(x)

• Loop through both keys and values, by using the items() method:

Jersey={10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'}
10 sachin
for x,y in jersey.items(): 5 Dravid
print(x,y) 45 Rohith
18 Kohli
Dictionary Membership Test
• We can test if a key is in a dictionary or not using the keyword in.
• Membership test is for keys only, not for values.
Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares) # Output: True

print(2 in squares) # Output: False


Write a Python script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are the square of the
keys.

d = dict()

# Iterate through numbers from 1 to 15 (inclusive).


for x in range(1, 16):
d[x] = x ** 2
print(d)

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144,
13: 169, 14: 196, 15: 225}
Write a Python program to sum all the items in a dictionary with out
using methods
my_dict = {'data1': 10, 'data2': 4, 'data3': 2}
sum=0;
for i in my_dict:
sum=sum+my_dict[i]
print(“sum:”,sum)
Sum : 16
Write a Python program to remove a key from a dictionary

myDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Print the original dictionary 'myDict'.


print(myDict)

if 'a' in myDict:
del myDict['a']
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(myDict)
{'b': 2, 'c': 3, 'd': 4}
Write a Python program to get the maximum and minimum values of a dictionary.

my_dict = {'x': 500, 'y': 5874, 'z': 560}


print("maximum value is",max(my_dict.values()))
print("minimum value is",min(my_dict.values()))
Python: Remove duplicates from Dictionary
my_dict = {'x': 500, 'y': 5874, 'z': 500}
result = {}

for key, value in my_dict.items():


if value not in result.values():
result[key] = value {'x': 500, 'y': 5874}
print(result)
Numpy Array in python
• An NumPy array/ndarray is a multidimensional container for collection of
homogeneous data; that is, all of the elements must be the same type.
• Numpy arrays are faster, more efficient than lists.
NumPy package:
• NumPy is a Python library used for working with arrays.
• It provides support for large, multi-dimensional arrays and matrices, along
with mathematical functions to operate on these arrays.
• NumPy is a fundamental package for scientific computing with Python.

Importing NumPy:
import numpy
Create a NumPy ndarray Object
• We can create a NumPy ndarray object by using the array() function.
import numpy as np

arr = np.array([1, 2, 3, 4, 5]) // 1-D Array

print(arr)
print(type(arr))
[1 2 3 4 5]
<class 'numpy.ndarray'>
2-D Arrays
• 2-D array is used to represent matrix
• A matrix is a two-dimensional data structure where numbers are
arranged into rows and columns.
Create Matrix in NumPy

import numpy as np

# create a 2x2 matrix 2x2 Matrix:


matrix1 = np.array([[1, 3], [[1 3]
[5, 7]]) [5 7]]
print("2x2 Matrix:\n",matrix1)
3x3 Matrix:
# create a 3x3 matrix [[ 2 3 5]
matrix2 = np.array([[2, 3, 5], [ 7 14 21]
[7, 14, 21], [ 1 3 5]]
[1, 3, 5]])
NumPy Array Attributes
import numpy as np

# create a 2-D array


array1 = np.array([[2, 4, 6],
[1, 3, 5]])

# check the dimension of array1


print(array1.ndim)

# return total number of elements in array1 2


print(array1.size)
6
# return a tuple that gives size of array in (2, 3)
each dimension
print(array1.shape)
Accessing the Elements of the Matrix
import numpy as np
A= np.array( [ [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10, 11, 12 ] ] )
print( "2nd element of 1st row of the matrix = “, A [0] [1] )
print( "3rd element of 2nd row of the matrix = ", A [1] [2] )
print( "Second row of the matrix = ",A[1] )
print( "last element of the last row of the matrix =", A[-1] [-1] )
2nd element of 1st row of the matrix = 5
3rd element of 2nd row of the matrix = 9
Second row of the matrix = [7 8 9]
last element of the last row of the matrix = 12
Matrix Operations using Numpy
1.Basic Matrix Operations
1.Addition
2.Subtraction
3.Multiplication
4.Division
2.Advanced Matrix Operations
1.Transpose
2.Inverse
Addition of Matrices
• Plus, operator (+) is used to add the elements of two matrices.

import numpy as np
X = np.array ( [ [ 8, 10 ], [ -5, 9 ] ] )
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] )
Z = X + Y #np.add(X,Y)
print (“Addition of Two Matrix : \n ", Z)

Addition of Two Matrix :


[[10 16]
[ 2 18]]
Subtraction of Matrices
• Minus operator (-) is used to subtract the elements of two matrices.

import numpy as np
X = np.array ( [ [ 8, 10 ], [ -5, 9 ] ] )
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] )
Z = X – Y #np.subtract(X,Y)
print (“Subtraction of Two Matrix : \n ", Z)

Substraction of Two Matrix :


[[ 6 4]
[-12 0]]
Multiplication of Matrices
• Multiplication operator (*) is used to multiply the elements of two
matrices element wise.

import numpy as np
X = np.array ( [ [ 8, 10 ], [ -5, 9 ] ] )
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] )
Z = X * Y #np.multiply(X,Y)
print ("Multiplication of Two Matrix : \n ", Z)

Multiplication of Two Matrix :


[[ 16 60]
[-35 81]]
Division of Matrices
• Division operator (/) is used to divide the elements of two matrices
element wise.

import numpy as np
X = np.array ( [ [ 8, 10 ], [ -5, 9 ] ] )
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] )
Z = X / Y #np. Divide(X,Y)
print ("Division of Two Matrix : \n ", Z)
Matrix Dot Products Calculation

• @/dot() method is used to calculate dot Product of two matrices .

import numpy as np
X = np.array ( [ [ 8, 1 ], [ 5, 2 ] ] )
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] )
Z = X @ Y
print ("dot product of Two Matrix : \n ", Z)

dot product of Two Matrix :


[[23 57]
[24 48]]
Transpose of a Matrix

• It is nothing but the interchange the rows and columns of a Matrix

import numpy as np
X = np.array ( [ [ 8, 1 ], [ 5, 2 ] ] )

print ( " Original Matrix is : \n ", X)


print ( " Transpose Matrix is : \n ", np.transpose(X))
Original Matrix is :
[[8 1]
[5 2]]
Transpose Matrix is :
[[8 5]
[1 2]]
Determinant of a Matrix in NumPy

• It is nothing but the interchange the rows and columns of a


Matrix
import numpy as np
A = np.array ( [ [ 8, 1 ], [ 5, 2 ] ] )

print ( " Original Matrix is : \n ", A)


print(" Determinant Matrix is : \n ",np.linalg.det(A))
Inverse of a Matrix

import numpy as np
A = np.array ( [ [ 8, 1 ], [ 5, 2 ] ] )
print ( " Original Matrix is : \n ", A)
print(" Inverse Matrix is : \n
",np.linalg.inv(A))
Original Matrix is :
[[8 1]
[5 2]]
Inverse Matrix is :
[[ 0.18181818 -0.09090909]
[-0.45454545 0.72727273]]
Reshaping arrays
• Reshaping means changing the shape of an array.
• The shape of an array is the number of elements in each dimension.
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(4,3)

print(newarr)
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Write a python program to apply basic matrix operations on matrices
Addition of Two Matrix :
import numpy as np [[10 16]
X = np.array ( [ [ 8, 10 ], [ -5, 9 ] ] ) [ 2 18]]
Subtraction of Two Matrix :
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] ) [[ 6 4]
[-12 0]]
print (“Addition of Two Matrix : \n ", X+Y) Multiplication of Two Matrix :
print ("Subtraction of Two Matrix : \n ", X-Y) [[ 16 60]
[-35 81]]
print ("Multiplication of Two Matrix : \n ", X*Y) Division of Two Matrix :
[[ 4. 1.66666667]
print ("Division of Two Matrix : \n ", X/Y) [-0.71428571 1. ]]
print ("dot product of Two Matrix : \n ", X@Y) dot product of Two Matrix :
[[ 86 138]
print ( " Transpose Matrix is : \n ", np.transpose(X)) [ 53 51]]
Transpose Matrix is :
print(" Inverse Matrix is : \n ",np.linalg.inv(X)) [[ 8 -5]
[10 9]]
Inverse Matrix is :
[[ 0.07377049 -0.08196721]
[ 0.04098361 0.06557377]]
Write a python program to apply basic matrix operations on matrices with looping
import numpy as np
X = np.array ( [ [ 8, 10 ],
[ -5, 9 ] ] )
Y = np.array ( [ [ 2, 6 ],
[ 7, 9 ] ] )
# Create a result matrix with the same dimensions
A = [[0, 0],[0, 0]]
S = [[0, 0],[0, 0]]
M = [[0, 0],[0, 0]]
D = [[0, 0],[0, 0]]
for i in range(len(X)):
for j in range(len(Y)):
A[i][j] = X[i][j] + Y[i][j]
S[i][j] = X[i][j] - Y[i][j]
M[i][j] = X[i][j] * Y[i][j]
D[i][j] = X[i][j] / Y[i][j]

print (“Addition of Two Matrix : \n ", A)


print ("Subtraction of Two Matrix : \n ", S)
print ("Multiplication of Two Matrix : \n ", M)
print ("Division of Two Matrix : \n ", D)
# Program to transpose a matrix using a nested loop

X = [[12,7],
[4 ,5],
[3 ,8]]

result = [[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]

for r in result: [12, 4, 3]


print(r) [7, 5, 8]
Mathematical methods
sum(): It returns the sum of array elements.
max(): It finds the maximum element in an array
min(): It finds the minimum element in an array
mean(): It computes the arithmetic mean (average) of the given data
var() : It Compute the variance of the given data
std(): It computes the standard deviation of the given data
np.sort() : This function returns a sorted copy of an array.
Write a python program to create an array with marks of 10 students . Find
minimum, maximum, average, variance, standard deviation of marks. Print in
ascending order also.
import numpy as np

a= np.array([15, 25, 36, 47, 58, 60, 75, 85, 95])

print("Max is:",np.max(a)) Max is: 95


print("Min is:",np.min(a)) Min is: 15
print("Average is:",np.mean(a)) Average is: 55.111111111111114
print("variance is:",np.var(a)) variance is: 650.9876543209876
print("SD is:",np.std(a)) SD is: 25.514459710544287
print("After sortng :",np.sort(a)) After sortng : [15 25 36 47 58 60 75 85 95]

You might also like