You are on page 1of 20

PYTHON – UNIT III

UNIT III Functions – Built in functions – function definition and calling - return statement –
void function – scope and lifetime of variables – args and kwargs – command line arguments -
Tuples – creation – basic tuple operations – tuple() function – indexing – slicing – built-in
functions used on tuples – tuple methods – packing – unpacking – traversing of tuples –
populating tuples – zip() function - Sets – Traversing of sets – set methods – frozenset.
Python Functions
The fundamentals of Python functions, including what they are, their syntax, their primary parts,
return keywords, and major types, will be covered in this tutorial. Additionally, we'll examine
several instances of Python function definitions.
What are Python Functions?
A function is a collection of related assertions that performs a mathematical, analytical, or
evaluative operation. A collection of statements called Python Functions returns the particular
task. Python functions are simple to define and essential to intermediate-level programming. The
exact criteria hold to function names as they do to variable names. The goal is to group up
certain often performed actions and define a function. We may call the function and reuse the
code contained within it with different variables rather than repeatedly creating the same code
block for different input variables.
User-defined and built-in functions are the two main categories of functions in Python. It helps
maintain the programme concise, unique, and well-structured.
Advantages of Functions in Python
Python functions have the following
o By including functions, we can prevent repeating the same code block repeatedly in a
program.
o Python functions, once defined, can be called many times and from anywhere in a
program.
o If our Python program is large, it can be separated into numerous functions which is
simple to track.
o The key accomplishment of Python functions is we can return as many outputs as we
want with different arguments.
However, calling functions has always been overhead in a Python program.
Syntax of Python Function
# An example Python Function
def function_name( parameters ):
# code block
The following elements make up to define a function, as seen above.
o The beginning of a function header is indicated by a keyword called def.
o function_name is the function's name that we can use to separate it from others. We will
use this name to call the function later in the program. In Python, name functions must
follow the same rules as naming variables.
o We pass arguments to the defined function using parameters. However, they are optional.

GOVT ARTS AND SCIENCE COLLEGE Page 1


PYTHON – UNIT III

o The function header is terminated by a colon (:).


o We can use a documentation string called docstring in the short form to explain the
purpose of the function.
o The body of the function is made up of several valid Python statements. The indentation
depth of the whole code block must be the same (usually 4 spaces).
o We can use a return expression to return a value from a defined function.
Example of a User-Defined Function
We will define a function that when called will return the square of the number passed to it as an
argument.
Code
# Example Python Code for User-Defined function
def square( num ):
"""
This function computes the square of the number.
"""
return num**2
object_ = square(6)
print( "The square of the given number is: ", object_ )
Output:
The square of the given number is: 36
Calling a Function
A function is defined by using the def keyword and giving it a name, specifying the arguments
that must be passed to the function, and structuring the code block.
After a function's fundamental framework is complete, we can call it from anywhere in the
program. The following is an example of how to use the a_function function.
Code
1. # Example Python Code for calling a function
2. # Defining a function
3. def a_function( string ):
4. "This prints the value of length of string"
5. return len(string)
6.
7. # Calling the function we defined
8. print( "Length of the string Functions is: ", a_function( "Functions" ) )
9. print( "Length of the string Python is: ", a_function( "Python" ) )
Output:
Length of the string Functions is: 9
Length of the string Python is: 6

GOVT ARTS AND SCIENCE COLLEGE Page 2


PYTHON – UNIT III

Pass by Reference vs. Pass by Value


All parameters in the Python programming language are provided by reference. It indicates that
if we alter the value of an argument inside of a function, the calling function will likewise reflect
the change. For example,
Code
1. # Example Python Code for Pass by Reference vs. Value
2. # defining the function
3. def square( item_list ):
4. '''''''This function will find the square of items in the list'''
5. squares = [ ]
6. for l in item_list:
7. squares.append( l**2 )
8. return squares
9.
10. # calling the defined function
11. my_list = [17, 52, 8];
12. my_result = square( my_list )
13. print( "Squares of the list are: ", my_result )
Output:
Squares of the list are: [289, 2704, 64]
Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
1) Default Arguments
A default argument is a kind of parameter that takes as input a default value if no value is
supplied for the argument when the function is called. Default arguments are demonstrated in the
following instance.
Code
1. # Python code to demonstrate the use of default arguments
2. # defining a function
3. def function( n1, n2 = 20 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.

GOVT ARTS AND SCIENCE COLLEGE Page 3


PYTHON – UNIT III

7.
8. # Calling the function and passing only one argument
9. print( "Passing only one argument" )
10. function(30)
11.
12. # Now giving two arguments to the function
13. print( "Passing two arguments" )
14. function(50,30)
Output:
Passing only one argument
number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
2) Keyword Arguments
A function called's arguments are linked to keyword arguments. When invoking a function with
keyword arguments, the user may tell whose parameter value it is by looking at the parameter
label.
We can remove certain arguments or arrange them in a different order since the Python
interpreter will connect the provided keywords to link the values with its parameters. Another
way to use keywords to invoke the function() method is as follows:
Code
1. # Python code to demonstrate the use of keyword arguments
2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing arguments without using keyword
8. print( "Without using keyword" )
9. function( 50, 30)
10.
11. # Calling function and passing arguments using keyword
12. print( "With using keyword" )
13. function( n2 = 50, n1 = 30)
Output:
Without using keyword
number 1 is: 50

GOVT ARTS AND SCIENCE COLLEGE Page 4


PYTHON – UNIT III

number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50
3) Required Arguments
The arguments given to a function while calling in a pre-defined positional sequence are required
arguments. The count of required arguments in the method call must be equal to the count of
arguments provided while defining the function.
We must send two arguments to the function function() in the correct order, or it will return a
syntax error, as seen below.
Code
1. # Python code to demonstrate the use of default arguments
2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to
be 30
8. print( "Passing out of order arguments" )
9. function( 30, 20 )
10.
11. # Calling function and passing only one argument
12. print( "Passing only one argument" )
13. try:
14. function( 30 )
15. except:
16. print( "Function needs two positional arguments" )
Output:
Passing out of order arguments
number 1 is: 30
number 2 is: 20
Passing only one argument
Function needs two positional arguments
4) Variable-Length Arguments
We can use special characters in Python functions to pass as many arguments as we want in a
function. There are two types of characters that we can use for this purpose:
1. *args -These are Non-Keyword Arguments
2. **kwargs -These are Keyword Arguments.

GOVT ARTS AND SCIENCE COLLEGE Page 5


PYTHON – UNIT III

Here is an example to clarify Variable length arguments


Code
1. # Python code to demonstrate the use of variable-length arguments
2. # Defining a function
3. def function( *args_list ):
4. ans = []
5. for l in args_list:
6. ans.append( l.upper() )
7. return ans
8. # Passing args arguments
9. object = function('Python', 'Functions', 'tutorial')
10. print( object )
11.
12. # defining a function
13. def function( **kargs_list ):
14. ans = []
15. for key, value in kargs_list.items():
16. ans.append([key, value])
17. return ans
18. # Paasing kwargs arguments
19. object = function(First = "Python", Second = "Functions", Third = "Tutorial")
20. print(object)
Output:
['PYTHON', 'FUNCTIONS', 'TUTORIAL']
[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]
return Statement
We write a return statement in a function to leave a function and give the calculated value when
a defined function is called.
Syntax:
1. return < expression to be returned as output >
The return statement, which is supplied as output when a particular job or function is finished,
might take the form of an argument, a statement, or a value. A declared function will return a
None object if no return statement is written.
Here is an example of a return statement in Python functions.
Code
1. # Python code to demonstrate the use of return statements
2. # Defining a function with return statement
3. def square( num ):

GOVT ARTS AND SCIENCE COLLEGE Page 6


PYTHON – UNIT III

4. return num**2
5.
6. # Calling function and passing arguments.
7. print( "With return statement" )
8. print( square( 52 ) )
9.
10. # Defining a function without return statement
11. def square( num ):
12. num**2
13.
14. # Calling function and passing arguments.
15. print( "Without return statement" )
16. print( square( 52 ) )
Output:
With return statement
2704
Without return statement
None
Scope and Lifetime of Variables
The scope of a variable refers to the domain of a program wherever it is declared. A function's
arguments and variables are not accessible outside the defined function. As a result, they only
have a local domain.
The lifespan of a variable in RAM is how long it stays there. A function's lifespan is the same as
that of its internal variables. They are taken away after we exit the function. Consequently, a
function does not keep the value of a variable from previous executions.
Here's a simple example of a variable's scope within a function.
Code
1. # Python code to demonstrate scope and lifetime of variables
2. #defining a function to print a number.
3. def number( ):
4. num = 50
5. print( "Value of num inside the function: ", num)
6.
7. num = 10
8. number()
9. print( "Value of num outside the function:", num)
Output:
Value of num inside the function: 50

GOVT ARTS AND SCIENCE COLLEGE Page 7


PYTHON – UNIT III

Value of num outside the function: 10


Here, we can see that num starts out with a value of 10. The value of num outside of the function
remained intact, even though the function number() changed the value of num to 50.
This is due to the fact that the function's internal variable num is different from the external
variable (local to the function). Despite having the same variable name, they are two separate
variables with separate scopes.
Variables beyond the function, on the contrary, are accessible within the function. These
variables have a global reach. We can retrieve their values inside the function but cannot alter or
change them. If we declare a variable global using the keyword global, we can also change the
variable's value outside the function.

Python has a set of built-in functions.

Function Description

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are true

any() Returns True if any item in an iterable object is true

Returns a readable version of an object. Replaces none-ascii


ascii()
characters with escape character

bin() Returns the binary version of a number

bool() Returns the boolean value of the specified object

bytearray() Returns an array of bytes

GOVT ARTS AND SCIENCE COLLEGE Page 8


PYTHON – UNIT III

bytes() Returns a bytes object

callable() Returns True if the specified object is callable, otherwise False

chr() Returns a character from the specified Unicode code.

Python Tuples
A Python Tuple is a group of items that are separated by commas. The indexing, nested objects,
and repetitions of a tuple are somewhat like those of a list, however unlike a list, a tuple is
immutable.
The distinction between the two is that while we can edit the contents of a list, we cannot alter
the elements of a tuple once they have been assigned.
Example
1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.
Features of Python Tuple
o Tuples are an immutable data type, which means that once they have been generated,
their elements cannot be changed.
o Since tuples are ordered sequences, each element has a specific order that will never
change.
Creating of Tuple:
To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (), each one
separated by a comma. Although it is not necessary to include parentheses, doing so is advised.
A tuple can contain any number of items, including ones with different data types (dictionary,
string, float, list, etc.).
Code:
# Python program to show how to create a tuple
1. # Creating an empty tuple
2. empty_tuple = ()
3. print("Empty tuple: ", empty_tuple)
4.
5. # Creating tuple having integers
6. int_tuple = (4, 6, 8, 10, 12, 14)
7. print("Tuple with integers: ", int_tuple)

GOVT ARTS AND SCIENCE COLLEGE Page 9


PYTHON – UNIT III

8.
9. # Creating a tuple having objects of different data types
10. mixed_tuple = (4, "Python", 9.3)
11. print("Tuple with different data types: ", mixed_tuple)
12. )
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
Tuples can be constructed without using parentheses. This is known as triple packing.
Code
1. # Python program to create a tuple without using parentheses
2. # Creating a tuple
3. tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
4. # Displaying the tuple created
5. print(tuple_)
6. # Checking the data type of object tuple_
7. print(type(tuple_) )
8. # Trying to modify tuple_
9. try:
10. tuple_[1] = 4.2
11. except:
12. print(TypeError )
Output:
(4, 5.7, 'Tuples', ['Python', 'Tuples'])
<class 'tuple'>
<class 'TypeError'>
The construction of a tuple from a single member might be hard.
Simply adding parenthesis around the element is insufficient. To be recognised as a tuple, the
element must be followed by a comma.
Code
1. # Python program to show how to create a tuple having a single element
2. single_tuple = ("Tuple")
3. print( type(single_tuple) )
4. # Creating a tuple that has only one element
5. single_tuple = ("Tuple",)
6. print( type(single_tuple) )
7. # Creating tuple without parentheses

GOVT ARTS AND SCIENCE COLLEGE Page 10


PYTHON – UNIT III

8. single_tuple = "Tuple",
9. print( type(single_tuple) )
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Accessing Tuple Elements
We can access the objects of a tuple in a variety of ways.
o Indexing
To access an object of a tuple, we can use the index operator [], where indexing in the tuple starts
from 0.
A tuple with 5 items will have indices ranging from 0 to 4. An IndexError will be raised if we try
to access an index from the tuple that is outside the range of the tuple index. In this case, an
index above 4 will be out of range.
We cannot give an index of a floating data type or other kinds because the index in Python must
be an integer. TypeError will appear as a result if we give a floating index.
The example below illustrates how indexing is performed in nested tuples to access elements.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
Output:
Python
Tuple
tuple index out of range

o Negative Indexing
Python's sequence objects support negative indexing.
The last item of the collection is represented by -1, the second last item by -2, and so on.
Code
# Python program to show how negative indexing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
# Printing elements using negative indices
print("Element at -1 index: ", tuple_[-1])

GOVT ARTS AND SCIENCE COLLEGE Page 11


PYTHON – UNIT III

print("Elements between -4 and -1 are: ", tuple_[-4:-1])


Output:
Element at -1 index: Collection
Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')
Slicing
Definition and Usage
The slice() function 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, which allows you to e.g. slice only
every other item.

Syntax
slice(start, end, step)
Parameter Values
Parameter Description

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 1

In Python, tuple slicing is a common practise and the most popular method for programmers to
handle practical issues. Think about a Python tuple. To access a variety of elements in a tuple,
you must slice it. One approach is to use the colon as a straightforward slicing operator (:).
We can use a slicing operator, a colon (:), to access a range of tuple elements.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
print("Elements between indices 1 and 3: ", tuple_[1:3])
# Using negative indexing in slicing
print("Elements between indices 0 and -4: ", tuple_[:-4])
# Printing the entire tuple by using the default start and end values.
print("Entire tuple: ", tuple_[:])
Output:
Elements between indices 1 and 3: ('Tuple', 'Ordered')
Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')
Deleting a Tuple

GOVT ARTS AND SCIENCE COLLEGE Page 12


PYTHON – UNIT III

A tuple's components cannot be altered, as was previously said. As a result, we are unable to get
rid of or remove tuple components.
However, a tuple can be totally deleted with the keyword del.
Code
1. # Python program to show how to delete elements of a Python tuple
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
4. # Deleting a particular element of the tuple
5. try:
6. del tuple_[3]
7. print(tuple_)
8. except Exception as e:
9. print(e)
10. # Deleting the variable from the global space of the program
11. del tuple_
12. # Trying accessing the tuple after deleting it
13. try:
14. print(tuple_)
15. except Exception as e:
16. print(e)
Output:
'tuple' object does not support item deletion
name 'tuple_' is not defined
Repetition Tuples in Python
Code
1. # Python program to show repetition in tuples
2. tuple_ = ('Python',"Tuples")
3. print("Original tuple is: ", tuple_)
4. # Repeting the tuple elements
5. tuple_ = tuple_ * 3
6. print("New tuple is: ", tuple_)
Output:
Original tuple is: ('Python', 'Tuples')
New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')
Tuple Methods
Python Tuples is a collection of immutable objects that is more like to a list. Python offers a few
ways to work with tuples. These two approaches will be thoroughly covered in this essay with
the aid of some examples.

GOVT ARTS AND SCIENCE COLLEGE Page 13


PYTHON – UNIT III

Examples of these methods are given below.


o Count () Method
The number of times the specified element occurs in the tuple is returned by the count () function
of Tuple.
Code
1. # Creating tuples
2. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
3. T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
4. # counting the appearance of 3
5. res = T1.count(2)
6. print('Count of 2 in T1 is:', res)
7. # counting the appearance of java
8. res = T2.count('java')
9. print('Count of Java in T2 is:', res)
Output:
Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index() Method:
The first instance of the requested element from the tuple is returned by the Index() function.
Parameters:
The element to be looked for.
o begin (Optional): the index used as the starting point for searching
o final (optional): The last index up until which the search is conducted
o Index() Method
Code
1. # Creating tuples
2. Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
3. # getting the index of 3
4. res = Tuple_data.index(3)
5. print('First occurrence of 1 is', res)
6. # getting the index of 3 after 4th
7. # index
8. res = Tuple_data.index(3, 4)
9. print('First occurrence of 1 after 4th index is:', res)
Output:
First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6
Tuple Membership Test

GOVT ARTS AND SCIENCE COLLEGE Page 14


PYTHON – UNIT III

Using the in keyword, we can determine whether an item is present in the given tuple or not.
Code
1. # Python program to show how to perform membership test for tuples
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
4. # In operator
5. print('Tuple' in tuple_)
6. print('Items' in tuple_)
7. # Not in operator
8. print('Immutable' not in tuple_)
9. print('Items' not in tuple_)
Output:
True
False
False
True
Iterating Through a Tuple
We can use a for loop to iterate through each element of a tuple.
Code
1. # Python program to show how to iterate over tuple elements
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Iterating over tuple elements using a for loop
5. for item in tuple_:
6. print(item)
Output:
Python
Tuple
Ordered
Immutable
Changing a Tuple
Tuples, as opposed to lists, are immutable objects.
This suggests that we are unable to change a tuple's elements once they have been defined. The
nested elements of an element can be changed, though, if the element itself is a changeable data
type like a list.
A tuple can be assigned to many values (reassignment).
Code
1. # Python program to show that Python tuples are immutable objects
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])

GOVT ARTS AND SCIENCE COLLEGE Page 15


PYTHON – UNIT III

4. # Trying to change the element at index 2


5. try:
6. tuple_[2] = "Items"
7. print(tuple_)
8. except Exception as e:
9. print( e )
10. # But inside a tuple, we can change elements of a mutable object
11. tuple_[-1][2] = 10
12. print(tuple_)
13. # Changing the whole tuple
14. tuple_ = ("Python", "Items")
15. print(tuple_)
Output:
'tuple' object does not support item assignment
('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4])
('Python', 'Items')
To merge multiple tuples, we can use the + operator. Concatenation is the term for this.
Using the * operator, we may also repeat a tuple's elements for a specified number of times. This
is already shown above.
The results of the operations + and * are new tuples.
Code
1. # Python program to show how to concatenate tuples
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Adding a tuple to the tuple_
5. print(tuple_ + (4, 5, 6))
Output:
('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)
Following are Some Advantages of Tuples over Lists:
Lists take longer than triples.
The code is protected from any unintentional changes thanks to tuples. It is preferable to store
non-changing data in "tuples" rather than "lists" if it is required by a programme.
If a tuple includes immutable values like strings, numbers, or another tuple, it can be used as a
dictionary key. Since "lists" are mutable, they cannot be utilized as dictionary keys.
Python – Pack and Unpack Tuples
Packing a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a tuple:
fruits = ("apple", "banana", "cherry")
print(fruits)

GOVT ARTS AND SCIENCE COLLEGE Page 16


PYTHON – UNIT III

Output
('apple', 'banana', 'cherry')
Unpacking a tuple:
But, in Python, we are also allowed to extract the values back into variables. This is called
"unpacking":
fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)
Output
apple
banana
cherry
Note: The number of variables must match the number of values in the tuple, if not, you must
use an asterisk to collect the remaining values as a list.
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the variable
name and the values will be assigned to the variable as a list:

Assign the rest of the values as a list called "red":


fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)
Output
apple
banana
['cherry', 'strawberry', 'raspberry']
Python zip()
The zip() function returns a zip object, which is an iterator of tuples where the first item in each
passed iterator is paired together, and then the second item in each passed iterator are paired
together etc.
If the passed iterators have different lengths, the iterator with the least items decides the length of
the new iterator.

GOVT ARTS AND SCIENCE COLLEGE Page 17


PYTHON – UNIT III

Syntax
zip(iterator1, iterator2, iterator3 ...)
Parameter Values
Parameter Description

iterator1, iterator2, iterator3 ... Iterator objects that will be joined together

If one tuple contains more items, these items are ignored:


a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica", "Vicky")

x = zip(a, b)
Output
(('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))
Python Sets
A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can
modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we
cannot directly access any element of the set by the index. However, we can print them all
together, or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces
{}. Python also provides the set() method, which can be used to create the set by the passed
sequence.
Example 1: Using curly braces
1. Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday

GOVT ARTS AND SCIENCE COLLEGE Page 18


PYTHON – UNIT III

Thursday
Sunday
Wednesday
Example 2: Using set() method
1. Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Su
nday"])
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:
{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or more


sets

difference_update() Removes the items in this set that are also included in
another, specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

GOVT ARTS AND SCIENCE COLLEGE Page 19


PYTHON – UNIT III

Python Frozenset
Definition and Usage
The frozenset() function returns an unchangeable frozenset object (which is like a set object,
only unchangeable).

Syntax
frozenset(iterable)
Parameter Values
Parameter Description

iterable An iterable object, like list, set, tuple etc.

Example
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
print(x)
frozenset({'apple', 'banana', 'cherry'})
More Examples
Try to change the value of a frozenset item.
This will cause an error:
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
x[1] = "strawberry"
Output
Traceback (most recent call last):
File "demo_ref_frozenset2.py", line 3, in <module>
x[1] = "strawberry"
TypeError: 'frozenset' object does not support item assignment

GOVT ARTS AND SCIENCE COLLEGE Page 20

You might also like