0% found this document useful (0 votes)
22 views76 pages

Sequences and Numpy

The document provides an overview of data structures in Python, focusing on lists, tuples, and sets. It explains how to create, access, modify, and perform operations on lists and tuples, along with various methods available for these data types. Additionally, it covers list comprehension and basic set operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views76 pages

Sequences and Numpy

The document provides an overview of data structures in Python, focusing on lists, tuples, and sets. It explains how to create, access, modify, and perform operations on lists and tuples, along with various methods available for these data types. Additionally, it covers list comprehension and basic set operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

Python

Programmin
g Language
Data structures
• Data structures are a way of organizing and storing data so
that they can be accessed and worked with efficiently.

T Seshu Chakravarthy Department Of Computer Science and Engineering


Data Types in Python

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

T Seshu Chakravarthy Department Of Computer Science and Engineering


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 ];

T Seshu Chakravarthy Department Of Computer Science and Engineering


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']]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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.

T Seshu Chakravarthy Department Of Computer Science and Engineering


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']

T Seshu Chakravarthy Department Of Computer Science and Engineering


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"]
['banana', 'cherry', 'orange']
print(thislist[-4:-1])

T Seshu Chakravarthy Department Of Computer Science and Engineering


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']

T Seshu Chakravarthy Department Of Computer Science and Engineering


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") ['apple', 'orange', 'banana', 'cherry']
print(thislist)
T Seshu Chakravarthy Department Of Computer Science and Engineering
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']
T Seshu Chakravarthy Department Of Computer Science and Engineering
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
T Seshu Chakravarthy Department Of Computer Science and Engineering
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]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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:
Language List: ['French', 'English', 'German', 'Spanish',
print('Language List: ', language) 'Portuguese']

T Seshu Chakravarthy Department Of Computer Science and Engineering


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))
T Seshu Chakravarthy Department Of Computer Science and Engineering
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.
T Seshu Chakravarthy Department Of Computer Science and Engineering
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]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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)

T Seshu Chakravarthy Department Of Computer Science and Engineering


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

T Seshu Chakravarthy Department Of Computer Science and Engineering


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)

T Seshu Chakravarthy Department Of Computer Science and Engineering


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)

T Seshu Chakravarthy Department Of Computer Science and Engineering


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]
• n=5
• combinations = [(x,y) for x in range(1,n+1) for y in range(1,n+1)]
• print("All possible combination of pairs from 1 to 5 are:",combinations)

T Seshu Chakravarthy Department Of Computer Science and Engineering


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.

T Seshu Chakravarthy Department Of Computer Science and Engineering


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"

T Seshu Chakravarthy Department Of Computer Science and Engineering


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 ":".

T Seshu Chakravarthy Department Of Computer Science and Engineering


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])
T Seshu Chakravarthy Department Of Computer Science and Engineering
Basic tuple Operations

T Seshu Chakravarthy Department Of Computer Science and Engineering


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

T Seshu Chakravarthy Department Of Computer Science and Engineering


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') ['a', 'e', 'i', 'o', 'u’]
['u', 'o', 'i', 'e', 'a']
print(sorted(p))
print(sorted(p,reverse=True))
T Seshu Chakravarthy Department Of Computer Science and Engineering
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)

T Seshu Chakravarthy Department Of Computer Science and Engineering


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}

T Seshu Chakravarthy Department Of Computer Science and Engineering


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

T Seshu Chakravarthy Department Of Computer Science and Engineering


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}
T Seshu Chakravarthy Department Of Computer Science and Engineering
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'}
T Seshu Chakravarthy Department Of Computer Science and Engineering
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]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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'}

T Seshu Chakravarthy Department Of Computer Science and Engineering


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'})

T Seshu Chakravarthy Department Of Computer Science and Engineering


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

T Seshu Chakravarthy Department Of Computer Science and Engineering


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’}

T Seshu Chakravarthy Department Of Computer Science and Engineering


Python Dictionary Methods
1. get()
2. pop()
3. Del
4. clear()
5. Items()
6. update()
7. keys()
8. values()
9. copy()

T Seshu Chakravarthy Department Of Computer Science and Engineering


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

T Seshu Chakravarthy Department Of Computer Science and Engineering


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: {}
T Seshu Chakravarthy Department Of Computer Science and Engineering
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)

T Seshu Chakravarthy Department Of Computer Science and Engineering


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)])

T Seshu Chakravarthy Department Of Computer Science and Engineering


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())
print(sales.values())

dict_keys(['apple', 'orange', 'grapes'])


dict_values([2, 3, 4])

T Seshu Chakravarthy Department Of Computer Science and Engineering


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)

T Seshu Chakravarthy Department Of Computer Science and Engineering


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

T Seshu Chakravarthy Department Of Computer Science and Engineering


Loop Through a Dictionary

• for loop can be used to iterate though each key in a dictionary.


Ex:
jersey = {10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'}
for x in jersey: 10
print(x) 5
45
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

T Seshu Chakravarthy Department Of Computer Science and Engineering


Loop Through a Dictionary

• You can also use the values() method to return values of a dictionary:

sachin
jersey = Dravid
{10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'} Rohith
for x in jersey.values(): Kohli
print(x)

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

jersey = {10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'}
for x,y in jersey.items(): 10 sachin
5 Dravid
print(x,y)
45 Rohith
18 Kohli

T Seshu Chakravarthy Department Of Computer Science and Engineering


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

T Seshu Chakravarthy Department Of Computer Science and Engineering


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}

T Seshu Chakravarthy Department Of Computer Science and Engineering


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

T Seshu Chakravarthy Department Of Computer Science and Engineering


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']

print(myDict)

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

{'b': 2, 'c': 3, 'd': 4}

T Seshu Chakravarthy Department Of Computer Science and Engineering


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
print(result)
{'x': 500, 'y': 5874}

T Seshu Chakravarthy Department Of Computer Science and Engineering


Link For programs on Dictionaries in python

• https://www.w3resource.com/python-exercises/dictionary/

T Seshu Chakravarthy Department Of Computer Science and Engineering


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

T Seshu Chakravarthy Department Of Computer Science and Engineering


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'>

T Seshu Chakravarthy Department Of Computer Science and Engineering


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.

T Seshu Chakravarthy Department Of Computer Science and Engineering


Create Matrix in NumPy

import numpy as np

# create a 2x2 matrix


matrix1 = np.array([[1, 3],
[5, 7]])

print("2x2 Matrix:\n",matrix1)

# create a 3x3 matrix 2x2 Matrix:


matrix2 = np.array([[2, 3, 5], [[1 3]
[7, 14, 21], [5 7]]
[1, 3, 5]])

print("\n3x3 Matrix:\n",matrix2) 3x3 Matrix:


[[ 2 3 5]
[ 7 14 21]
[ 1 3 5]]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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


print(array1.size)

# return a tuple that gives size of array in each


dimension
print(array1.shape) 2
6
# check the data type of array1 (2, 3)
print(array1.dtype) int64

T Seshu Chakravarthy Department Of Computer Science and Engineering


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

T Seshu Chakravarthy Department Of Computer Science and Engineering


Matrix Operations using Numpy

1.Basic Matrix Operations


1. Addition
2. Subtraction
3. Multiplication
4. Division
2.Advanced Matrix Operations
1. Transpose
2. Inverse

T Seshu Chakravarthy Department Of Computer Science and Engineering


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]]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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]]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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]]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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)

Multiplication of Two Matrix :


[[ 4.0 1.66],
[-0.71 1.0]]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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]]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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]]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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))

T Seshu Chakravarthy Department Of Computer Science and Engineering


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]]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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]]

T Seshu Chakravarthy Department Of Computer Science and Engineering


Write a python program to apply basic matrix operations on matrices
Addition of Two Matrix :
[[10 16]
[ 2 18]]
import numpy as np Subtraction of Two Matrix :
[[ 6 4]
X = np.array ( [ [ 8, 10 ], [ -5, 9 ] ] ) [-12 0]]
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] ) Multiplication of Two Matrix :
[[ 16 60]
print (“Addition of Two Matrix : \n ", X+Y) [-35 81]]
print ("Subtraction of Two Matrix : \n ", X-Y) Division of Two Matrix :
[[ 4. 1.66666667]
print ("Multiplication of Two Matrix : \n ", X*Y) [-0.71428571 1. ]]
print ("Division of Two Matrix : \n ", X/Y) dot product of Two Matrix :
[[ 86 138]
print ("dot product of Two Matrix : \n ", X@Y) [ 53 51]]
print ( " Transpose Matrix is : \n ", Transpose Matrix is :
[[ 8 -5]
np.transpose(X)) [10 9]]
print(" Inverse Matrix is : \n ",np.linalg.inv(X)) Inverse Matrix is :
[[ 0.07377049 -0.08196721]
[ 0.04098361 0.06557377]]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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)

T Seshu Chakravarthy Department Of Computer Science and Engineering


# 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:
print(r)
[12, 4, 3]
[7, 5, 8]

T Seshu Chakravarthy Department Of Computer Science and Engineering


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.

T Seshu Chakravarthy Department Of Computer Science and Engineering


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))
print("Min is:",np.min(a))
print("Average is:",np.mean(a))
print("variance is:",np.var(a))
print("SD is:",np.std(a))
print("After sortng :",np.sort(a))
Max is: 95
Min is: 15
Average is: 55.111111111111114
variance is: 650.9876543209876
SD is: 25.514459710544287
After sortng : [15 25 36 47 58 60 75 85 95]

T Seshu Chakravarthy Department Of Computer Science and Engineering

You might also like