Chapter 4
Chapter 4
Tuples
Tuple is a type of sequence data type and Collection of items that are indexed, ordered and
immutable.
cannot update, delete individual value Delete entire
tuple using del
Creating tuples:
Represent tuple by () parenthesis.
Tuple items can be of any data type
Syntax : Tuple_name=(tiem1,item2,itemt3…) Example:
T1=(“python”,”java”,”perl”)
T2=(1,2,3)
T3=(1.3,5.6,7.8)
T4=(“python”,6,7.8,True)
To write a tuple containing a single value you have to include a comma, even though there is
only one value
T5=(“python”,) T6=(100,)
• Using the tuple() method to make a tuple Use double round-brackets(( )) Syntax:
tuple_name=tuple((item1,item2,item3….)) Example:
T1=tuple(("python","java"))
T2=tuple((1,2,3))
T3=tuple((1.3,4.5)) T4=tuple(("java",6.8,True)) print(T1,T2,T3,T4)
Output:
1st item= java
2nd item= 6.8
index 0 to 3= ('java', 6.8, True, 5)
2.Negative index Ex:
T4=(“python”,10,6.8,True)
T6=("java",6.8,True,5,6,7) print("1st item=",T4[-
1]) print("2nd item=",T4[-2]) print("index -2 to -
4=",T6[-4:-1])
Output:
1st item= True 2nd item= 6.8 index -2 to -4=
(True, 5, 6)
Built-in-functions on tuples
len(),
max(),
min(),
sum(),
sorted(),
slice(),
type(),
id()
• len():
len() returns the number of elements in the tuple Syntax: len(tuple) tuple:-parameter, for which
number of elements to be counted Ex:
T5=(40,30,20,10,50)
T4=('a',10,300,40.6,'e','f','g‘,True) print("length of tuple
T5=",len(T5)) print("length of tuple T4=",len(T4))
tuple − parameter, This is a tuple from which max valued element to be returned.
min(): returns the elements from the tuple with minimum value.
Tuple should only contain string or other type. Syntax: min(tuple)
tuple − parameter, This is a tuple from which min valued element to be returned
sum(): returns the elements from the tuple with total sum of all the elements
Tuple should not contain string.
Syntax: sum(tuple)
tuple − parameter, This is a tuple from which sum of all the element to be returned
Ex:
T5=(40,30,20,True,50,10.8,False) T3=("A","b","a","c")
print("maximum value of T5=",max(T5)) print("minimum
value of T5=",min(T5)) print("sum of T5=",sum(T5))
print("max of T3=",max(T3)) print("min of T3",min(T3))
sorted(): returns the elements from the tuple with sorted order
Tuple should only contain string or other type. Syntax: sorted(tuple)
tuple − parameter, This is a tuple from which sorted order of element to be returned.
Ex:
T5=(40,30,20,10.8,50,True,False) T3=("A","b","a","c“)
print("sorted order of T5=",sorted(T5)) print("sorted order of
T3=",sorted(T3)) Output:
sorted order of T5= [False, True, 10.8, 20, 30, 40, 50] sorted order of T3= ['A', 'a', 'b', 'c']
slice(): returns a slice object.
A slice object is used to specify how to slice a sequence. You can specify where to start the slicing,
and where to end. You can also specify the step
Create a tuple and a slice object Syntax: slice(start, end, step)
Output:
('a', 'd', 'g')
type():returns the type of the specified object
id():Return the unique id of a tuple object
• The id is the object's memory address, and will be different for each time you run the program
Ex:
T5=(40,30,20,10.8,50,True,False) print(type(T5))
print(id(T5))
Output:
<class 'tuple'>
2619181412704
Tuple Methods
1. Count() Method
The count() method for tuples tells you how many times a particular item appears in the tuple.
tuple.count(element)
# Define a tuple
my_tuple = (1, 2, 3, 4, 2, 2, 5)
count_of_2 = my_tuple.count(2)
Output
2.index( ) method
Search the tuple specified the value and return the position where it found.
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)//output: 3
Operations on tuples:
1. Indexing: Access individual elements of a tuple using square brackets and an index.
Indexing starts from 0.
Example:
my_tuple = (1, 2, 3)
print(my_tuple[0]) # Output: 1
2. Slicing: Retrieve a subset of elements from a tuple using the colon `:` operator.
Example:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)
3. Concatenation: Join two or more tuples together using the `+` operator
Example:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result_tuple = tuple1 + tuple2
print(result_tuple) # Output: (1, 2, 3, 4, 5, 6)
5,Deleting a tuple: Since tuples are immutable, it is not possible to delete individual elements of
a tuple, however we can delete the whole tuple itself using del statement. Example:
my_tuple = (1, 2)
del my_tuple # tuple will be deleted from the memory
print(my_tuple) #NameError because tuple is deleted
Output:
My_set2={ r,b,m}
My_set2={ r,b,m}
Print(My_set1 ! = My_set2)//output:false
Python Sets
In Python, a set is an unordered collection of unique elements. Sets are defined using curly
braces `{ }` or by using the `set( )` constructor. Sets do not allow duplicate values, and the order
of elements is not preserved.
Creating a Set
In Python, we create sets by placing all the elements inside curly braces { }, separated by
comma. A set can have any number of items and they may be of different types (integer, float,
tuple, string etc.). Python also provides the set( ) method, which can be used to create the set by
the passed sequence. But a set cannot have mutable elements like lists, sets or dictionaries as its
elements.
Example:
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id) vowel_letters
= {'a', 'e', 'i', 'o', 'u'} print('Vowel Letters:',
vowel_letters) mixed_set = {'Hello', 101, -2,
'Bye'} print('Set of mixed data types:',
mixed_set) set1=set(["Prashanth",1070])
Operations on set
Python provides several built-in data structures and methods for performing set
operations. Here are some commonly used set operations in Python.
1. Creating a Set:
Sets can be created using curly braces `{ }` or the `set( )` constructor.
# Using curly braces
my_set = {1, 2, 3}
# Using set() constructor
my_set = set([1, 2, 3])
2. Union:
The union operation combines two sets and returns a new set containing all unique elements
from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # or set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
3. Intersection:
The intersection operation returns a new set that contains elements common to both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2) # or set1 & set2
print(intersection_set) # Output: {3}
4. Difference:
The difference operation returns a new set that contains elements present in the first set but not
in the second set.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2) # or set1 - set2
print(difference_set) # Output: {1, 2}
5.Symmetric Difference:
The symmetric operation returns a new set that contains elements present in
set1 = {1, 2, 3}
set2 = {3, 4, 5}
sym_diff_set = set1.symmetric_difference(set2) # or set1 ^ set2
print(sym_diff_set) # Output: {1, 2, 4, 5}
2. remove(element):
Removes an element from the set. Raises a `KeyError` if the element is not found.
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}
3. discard(element):
Removes an element from the set if it exists. Does not raise an error if the element is not found.
my_set = {1, 2, 3}
my_set.discard(2)
print(my_set) # Output: {1, 3}
4. pop( ):
Removes and returns an arbitrary element from the set. Raises a `KeyError` if the set is empty.
my_set = {1, 2, 3}
popped_element = my_set.pop()
print(popped_element) # Output: 1
print(my_set) # Output: {2, 3}
5.clear( ):
Removes all elements from the set, making it empty.
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()
6.copy( ):
Returns a shallow copy of the set.
my_set = {1, 2, 3}
new_set = my_set.copy()
print(new_set) # Output: {1, 2, 3}
7.len( ):
Returns the number of elements in the set.
my_set = {1, 2, 3}
print(len(my_set)) # Output: 3
8. isdisjoint()
Ex:
z = x.isdisjoint(y)
print(z)
o/p: True
9.issubset()
z = x.issubset(y)
print(z)
o/p:True
10. intersection()
Return a set that contains the items that exist in both set x, and set y:
z = x.intersection(y)
print(z)
o/p: {“apple”}
11. union()
Return a set that contains all items from both sets, duplicates are excluded:
z = x.union(y)
print(z)
The all() function returns True if all elements in the given iterable are true. If not, it returns False.
Example
print(result)
# Output: True
2.any()
The any() function returns True if any element of an iterable is True. If not, it returns False.
Example
print(result)
# Output: True
3.len()
print(length)
# Output: 3
4.sum()
The sum() function adds the items of an iterable and returns the sum.
Example
print(total_marks)
# Output: 339
5.sort()
The sorted() method sorts the elements of the given iterable in ascending order and returns it.
Example
print(sorted_numbers)
7.min()
The min() function returns the smallest item in an iterable. It can also be used to find the smallest
item between two or more parameters.
Example
print(min_number)
# Output: -4
8.max()
The max() function returns the largest item in an iterable. It can also be used to find the largest item
between two or more parameters.
Example
max_number = max(numbers)
print(max_number)//output 34
Exception: exception is defined as an event that occurs during the execution of a program and
disrupts the normal flow of program instructions
# Code that will always execute, regardless of whether an exception occurred or not #
example
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ValueError:
print("Invalid input. Please enter valid integers.")
except ZeroDivisionError:
In Python, classes and objects are fundamental concepts of object-oriented programming (OOP).
Class :A class is a blueprint or a template that defines the characteristics and behavior of an object
Creating classes: A Python class starts with the reserved word 'class', followed by the class name
and a colon(:).
Syntax: class ClassName:
statements
Example:
1. class Person:
2. def __init__(self, name, age):
3. # This is the constructor method that is called when creating a new Person object
4. # It takes two parameters, name and age, and initializes them as attributes of the object
5. self.name = name
6. self.age = age
7. def greet(self):
8. # This is a method of the Person class that prints a greeting message
9. print("Hello, my name is " + self.name)
Objects in Python:
Syntax:
Example:
Code:
1. class Person:
2. def __init__(self, name, age):
3. self.name = name
4. self.age = age
5. def greet(self):
6. print("Hello, my name is " + self.name)
7.
8. # Create a new instance of the Person class and assign it to the variable person1
9. person1 = Person("Ayan", 25)
10. person1.greet()
Output:
self-parameter
The self-parameter refers to the current instance of the class and accesses the class variables.
_ _init_ _ method
In order to make an instance of a class in Python, a specific function called __init__ is called.
Although it is used to set the object's attributes, it is often referred to as a constructor.
Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
In Python, the method the __init__() simulates the constructor of the class. This method is called
when the class is instantiated. It accepts the self-keyword as a first argument which allows
accessing the attributes or method of the class.
We can pass any number of arguments at the time of creating the class object, depending upon
the __init__() definition. It is mostly used to initialize the class attributes. Every class must have
a constructor, even if it simply relies on the default constructor.
Example
1. class Employee:
2. def __init__(self, name, id):
3. self.id = id
4. self.name = name
5.
6. def display(self):
7. print("ID: %d \nName: %s" % (self.id, self.name))
8.
9.
10. emp1 = Employee("John", 101)
11. emp2 = Employee("David", 102)
12.
13. # accessing display() method to print employee 1 information
14.
15. emp1.display()
16.
17. # accessing display() method to print employee 2 information
18. emp2.display()
Output:
ID: 101
Name: John
ID: 102
Name: David
1.Python Non-Parameterized Constructor
The non-parameterized constructor uses when we do not want to manipulate the value or the
constructor that has only self as an argument. Consider the following example.
Example
1. class Student:
2. # Constructor - non parameterized
3. def __init__(self):
4. print("This is non parametrized constructor")
5. def show(self,name):
6. print("Hello",name)
7. student = Student()
8. student.show("John")
2.Python Parameterized Constructor
The parameterized constructor has multiple parameters along with the self. Consider the following
example.
Example
1. class Student:
2. # Constructor - parameterized
3. def __init__(self, name):
4. print("This is parametrized constructor")
5. self.name = name
6. def show(self):
7. print("Hello",self.name)
8. student = Student("John")
9. student.show()
Output:
When we do not include the constructor in the class or forget to declare it, then that becomes the
default constructor. It does not perform any task but initializes the objects. Consider the following
example.
Example
1. class Student:
2. roll_num = 101
3. name = "Joseph"
4.
5. def display(self):
6. print(self.roll_num,self.name)
7.
8. st = Student()
9. st.display()
Output:
101 Joseph
4.More than One Constructor in Single class
Let's have a look at another scenario, what happen if we declare the two same constructors in the
class.
Example
1. class Student:
2. def __init__(self):
3. print("The First Constructor")
4. def __init__(self):
5. print("The second contructor")
6. st = Student()
Output:
We can also create multiple objects from a single class. For example,
# define a class
class Employee:
# define a property
employee_id = 0
output:
Employee ID: 1001
Employee ID: 1002
Objects as arguments
Using object we call instance methods, modify methods, also We can call object as
arguments,
Syntax: classname.methodname(object)
Output:
101 Joseph
output:7
Type of ERROR
1. Syntax Errors
A syntax error occurs in Python , such as inappropriate indentation, erroneous keyword usage, or
incorrect operator use. Syntax errors prohibit the code from running, and the interpreter displays
an error message that specifies the problem and where it occurred in the code. Here's an example
of a Python syntax error:
x = 10
if x == 10
print("x is 10")
2.TypeError:
x = "10"
y=5
Z=x+y
print(z)
When the above code is executed in an IDE, we get the following error message:
An IndexError is raised in Python when we try to access an index of a sequence (such as a string,
list, or tuple) that is out of range.
When the above code is executed in an IDE, we get the following error message:
In Python, an AttributeErroris raised when you try to access an attribute or method of an object
that does not exist or is not defined for that object.
A NameError in Python is raised when the interpreter encounters a variable or function name
that it cannot find in the current scope.
x=5
y = 10
z = calculate_sum(x, w)
print(z)
When the above code is run in an IDE, we get the following output:
Traceback (most recent call last):
File "c:\Users\name\OneDrive\Desktop\demo.py", line 7, in <module>
Z = calculate_sum(x, w)
^
NameError: name 'w' is not defined
Z = calculate_sum(x, w)
^
NameError: name 'w' is not defined
6.KeyError
In simple terms, KeyError is an exception raised by a python program when we try to access a
value from a dictionary with a key that is not present in the dictionary.
myDict = {1: 1, 2: 4, 3: 9}
print(myDict[9])
7.ZeroDivisionError
a = 10
b=0
print(a/b)
In this example, a number a is attempted to be divided by another number b, whose value is zero,
leading to a ZeroDivisionError:
of your code is inconsistent within a block (e.g., mixing tabs and spaces, or using the
wrong number of spaces), Python will raise an IndentationError.fname = "Gaurav"
lname = "Siyal"
print("You're Gaurav")
else:
8.FileNotFoundError
that is raised when a program tries to access a file that doesn’t exist. This error typically
occurs when you attempt to perform file operations like opening, reading, writing, or
deleting a file. Python cannot find the specified file at the provided path or location.
file1 = open("abc.txt")
For instance:
Python
int("hello")
This code will raise a ValueError because we’re trying to convert a non-numeric string
into an integer.