Module 4
Module 4
Module 4
• Numbers
• Booleans
• Strings
• List
• Tuple
• Set
• Dictionary
List
Ex:
• list1 = ['physics', 'chemistry', 1997, 2000];
• list2 = [1, 2, 3, 4, 5 ];
How to create a list?
• 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?
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", "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:
Insert Items:
• The insert() method inserts an item at the specified index:
• If you do not specify the index, the pop() method removes the last item.
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.
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
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]
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")
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
• 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.
• 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
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
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,
• 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.
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:
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
• 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
d = dict()
{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
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.
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
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
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)
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)
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)
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
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)
import numpy as np
X = np.array ( [ [ 8, 1 ], [ 5, 2 ] ] )
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
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]
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]