[go: up one dir, main page]

0% found this document useful (0 votes)
10 views27 pages

Chapter 4

This document provides an overview of tuples and sets in Python, detailing their properties, methods, and operations. It explains how to create, access, and manipulate tuples, as well as perform various operations on sets, including union, intersection, and difference. Additionally, it covers built-in functions and methods available for both data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views27 pages

Chapter 4

This document provides an overview of tuples and sets in Python, detailing their properties, methods, and operations. It explains how to create, access, and manipulate tuples, as well as perform various operations on sets, including union, intersection, and difference. Additionally, it covers built-in functions and methods available for both data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

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)

• Accessing Values in Python Tuples


By index (positive and negative index)
Syntax: tuple_name[ index number]
1.Positive index
Ex:
T4=(“python”,6.8,10,True)
T6=("java",6.8,True,5,6,7) print("1st
item=",T4[0]) print("2nd item=",T4[1])
print("index 0 to 3=",T6[0:4])

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

Output:length of tuple T5= 5

length of tuple T4=9

max():returns the elements from the tuple with maximum value


Tuple should only contain string or other type. Syntax:
max(tuple)

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

Output: maximum value of T5= 50


minimum value of T5= False sum of
T5= 151.8 max of T3= c min of T3 A

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)

Start Optional. An integer number specifying at which


position to start the slicing. Default is 0

End An integer number specifying at which position to end


the slicing

Step Optional. An integer number specifying the step of the


slicing. Default is

Ex-1: using start and end


#tuple creation
T5=(40,30,20,10.8,50,True,False) #creating tuple
object x=slice(0,2) print("after slicing=",T5[x])
Output:
after slicing= (40, 30) Ex-2: using only
end
T4=('a',10,300,40.6,'e','f','g',True) y=slice(4)
print("after slicing=",T4[y]) Output:
after slicing= ('a', 10, 300, 40.6)
Ex-3 using start,end,step a = ("a", "b", "c", "d", "e", "f", "g", "h") x =
slice(0, 8, 3) print(a[x])

Output:
('a', 'd', 'g')
type():returns the type of the specified object
id():Return the unique id of a tuple object

• All objects in Python has its own unique id.

• The id is assigned to the object when it is created.

• 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.

Syntax of Count Method

tuple.count(element)

Element is the element that is required to be counted.

Example 1- Use the Tuple count() method in Python

# Define a tuple

my_tuple = (1, 2, 3, 4, 2, 2, 5)

count_of_2 = my_tuple.count(2)

print("The number 2 appears", count_of_2, "times in the tuple.")

Output

The number 2 appears 3 times in the tuple.

2.index( ) method

Search the tuple specified the value and return the position where it found.

Example 1- Use the Tuple index() method in Python

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)

4.repetation/Multiplication: Create a new tuple by repeating the elements of an existing tuple


using the
`*` operator.
Example:
my_tuple = (1, 2)
result_tuple = my_tuple * 3
print(result_tuple) # Output: (1, 2, 1, 2, 1, 2)

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:

6.Memebership and comparison


Return true, Particular element exist in a particular set, otherwise false called membership
operation.
Ex:1 .Memebership
My_set={ r,b,m}
print('z' in my_set)//o/p:False
print('r' in my_set)//True
print('b' not in my_set)//True

comparison: compare the two set using comparison operator(==,!=,<=,>=)

My_set2={ r,b,m}

My_set2={ r,b,m}

Print(My_set1 = = My_set2)//output: true

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

print('created set using set( ) method:',set1)


Output:

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

Either on set,but not in intersection.

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}

Python set methods


Python provides several built-in methods for performing operations on sets. Here are some
commonly used methods on sets
1. add(element): Adds an element to the set.
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

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:

Return True if no items in set x is present in set y:

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


y = {"google", "microsoft", "facebook"}

z = x.isdisjoint(y)

print(z)

o/p: True
9.issubset()

Return True if all items in set x are present in set y:

x = {"a", "b", "c"}


y = {"f", "e", "d", "c", "b", "a"}

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:

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


y = {"google", "microsoft", "apple"}

z = x.intersection(y)

print(z)

o/p: {“apple”}
11. union()

Return a set that contains all items from both sets, duplicates are excluded:

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


y = {"google", "microsoft", "apple"}

z = x.union(y)

print(z)

o/p:{ {"apple", "banana", "cherry","google", "microsoft"}

Set Built-in function


1.all()

The all() function returns True if all elements in the given iterable are true. If not, it returns False.
Example

boolean_list = ['True', 'True', 'True']

# check if all elements are true


result = all(boolean_list)

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

boolean_list = ['True', 'False', 'True']

# check if any element is true


result = any(boolean_list)

print(result)

# Output: True
3.len()

The len() function returns the number of items (length) in an object.


Example

languages = ['Python', 'Java', 'JavaScript']

# compute the length of languages


length = len(languages)

print(length)

# Output: 3

4.sum()

The sum() function adds the items of an iterable and returns the sum.
Example

marks = [65, 71, 68, 74, 61]

# find sum of all marks


total_marks = sum(marks)

print(total_marks)

# Output: 339

5.sort()

The sorted() method sorts the elements of the given iterable in ascending order and returns it.
Example

numbers = [4, 2, 12, 8]

# sort the list in ascending order


sorted_numbers = sorted(numbers)

print(sorted_numbers)

# Output: [2, 4, 8, 12]


6.enumarate()
The enumerate() function adds a counter to an iterable and returns it as an enumerate
Example

languages = ['Python', 'Java', 'JavaScript']

# enumerate the list


enumerated_languages = enumerate(languages)

# convert enumerate object to list


print(list(enumerated_languages))

# Output: [(0, 'Python'), (1, 'Java'), (2, 'JavaScript')]

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

numbers = [9, 34, 11, -4, 27]

# find the smallest number


min_number = min(numbers)

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

numbers = [9, 34, 11, -4, 27]

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

Exception handling using try, catch and finally

1) try: block lets you test a block of code for errors.


2) except: block lets you handle the error.
3) else: block lets you execute code when there is no error
4) finally: Always execute, block lets you execute code, regardless of the result of the try- and
except blocks.
Syntax:
try:
# Code that may raise an exception
except ExceptionType1:
# Code to handle ExceptionType1
#
except ExceptionType2:
# Code to handle ExceptionType2
#
else:
# Code to execute if no exception is raised
finally:

# 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:

print("Error: Division by zero is not allowed.")


else:

print("No exceptions occurred.")


finally:

print("Program execution complete.")

Object Oriented Programming

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:

An object is a particular instance of a class

Syntax:

1. # Declare an object of a class


2. object_name = Class_Name(arguments)

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:

"Hello, my name is Ayan"

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.

Creating the constructor in python

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.

Consider the following example to initialize the Employee class attributes.

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:

This is parametrized constructor


Hello John
3.Python Default Constructor

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:

The Second Constructor

Create Multiple Objects of Python Class

We can also create multiple objects from a single class. For example,
# define a class
class Employee:
# define a property
employee_id = 0

# create two objects of the Employee class


employee1 = Employee()
employee2 = Employee()

# access property using employee1


employee1.employeeID = 1001
print(f"Employee ID: {employee1.employeeID}")

# access properties using employee2


employee2.employeeID = 1002
print(f"Employee ID: {employee2.employeeID}")

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)

10. class Student:


11. roll_num = 101
12. name = "Joseph"
13.
14. def display(self):
15. print(self.roll_num,self.name)
16.
17. st = Student()
// Objects as arguments
18.
19. Student.display(st)
20. st.display()

Output:
101 Joseph

Object as return values


We can also use object to return method values. After instantiation, passing arguments
to return instance method values.
Instance methods it has 2 types
Accessors method: fetching value from instance variable
Mutators method: to modify instance variable value Using object we can modify instance
variable.
class emp:
def –init—(self,x,y):
self.x=x
self.y=y
def sum(self)
return(self.x+self.y)
e=emp(3,4)
print(e.sum())

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:

In Python, a TypeError is raised when an operation or function is applied to an object of an


inappropriate type. This can happen when trying to perform arithmetic or logical operations on
incompatible data types or when passing arguments of the wrong type to a function. Here's an
example of a TypeError in Python:

x = "10"
y=5
Z=x+y
print(z)
When the above code is executed in an IDE, we get the following error message:

Traceback (most recent call last):


File "c:\Users\name\OneDrive\Desktop\demo.py", line 3, in <module>
Z=x+y
~~^~~
TypeError: can only concatenate str (not "int") to str
3. IndexError

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.

my_list = [100, 200, 300, 400, 500]


print(my_list[5])

When the above code is executed in an IDE, we get the following error message:

Traceback (most recent call last):


File "c:\Users\name\OneDrive\Desktop\demo.py", line 2, in <module>
print(my_list[p
~~^~~
IndexError: list index out of range
4.AttributeError

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.

my_string = "Hello, world!"


my_string.reverse()
5 NameError:

A NameError in Python is raised when the interpreter encounters a variable or function name
that it cannot find in the current scope.

def calculate_sum(a, b):


total = a + b
return total

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("The dictionary is:", myDict)

print(myDict[9])

7.ZeroDivisionError

A ZeroDivisionError occurs in Python when a number is attempted to be divided by zero. Since


division by zero is not allowed in mathematics, attempting this in Python code raises
a ZeroDivisionError.

Python ZeroDivisionError Example

Here’s an example of a Python ZeroDivisionError thrown due to division by zero:

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:

File "test.py", line 3, in <module>


print(a/b)
ZeroDivisionError: division by zero
7. indentation error

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"

if fname == "Gaurav" and lname == "Siyal":

print("You're Gaurav")

else:

print("You're somebody 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")

FileNotFoundError Traceback (most recent call last)


<ipython-input-1-e02672f25e85> in <cell line: 1>()
----> 1 file1 = open("abc.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'
9. ValueError

A ValueError in Python is raised when a function or operation receives an argument


with a correct type but an inappropriate value. It signifies that the value you provided is
not suitable for a specific context or function.

For instance:

Python

int("hello")

This code will raise a ValueError because we’re trying to convert a non-numeric string
into an integer.

You might also like