0% found this document useful (0 votes)
109 views59 pages

Unit Iii Python

The document discusses functions in Python including built-in functions, defining user-defined functions, function parameters, return values, nested functions, and the return statement. It provides examples of different types of functions and how to call functions in Python.

Uploaded by

Master Kingdom
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)
109 views59 pages

Unit Iii Python

The document discusses functions in Python including built-in functions, defining user-defined functions, function parameters, return values, nested functions, and the return statement. It provides examples of different types of functions and how to call functions in Python.

Uploaded by

Master Kingdom
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/ 59

CCS 62 – PYTHON PROGRAMMING

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.

FUNCTIONS IN PYTHON

 Python Functions is a block of statements that return the specific task.

 The idea is to put some commonly or repeatedly done tasks together and make a function
so that instead of writing the same code again and again for different inputs, we can do
the function calls to reuse code contained in it over and over again.

Some Benefits of Using Functions

 Increase Code Readability


 Increase Code Reusable

Python Function Declaration

The syntax to declare a function is:

Types of Functions in Python

There are mainly two types of functions in Python.

 Built-in library function: These are Standard functions in Python that are available to
use.
 User-defined function: We can create our own functions based on our requirements.

UNIT III Page 1


CCS 62 – PYTHON PROGRAMMING

Creating a Function

Use the following steps to to define a function in Python.

 Use the def keyword with the function name to define a function.
 Next, pass the number of parameters as per your requirement. (Optional).
 Next, define the function body with a block of code. This block of code is nothing but the
action you wanted to perform.
In Python, no need to specify curly braces for the function body. The only indentation is
essential to separate code blocks. Otherwise, you will get an error.

Syntax of creating a function

def function_name(parameter1, parameter2):


# function body
# write some action
return value

 function_name: Function name is the name of the function. We can give any name to
function.
 parameter: Parameter is the value passed to the function. We can pass any number of
parameters. Function body uses the parameter‟s value to perform an action
 function_body: The function body is a block of code that performs some task. This block
of code is nothing but the action you wanted to accomplish.
 return value: Return value is the output of the function.

Fig : Python Functions

UNIT III Page 2


CCS 62 – PYTHON PROGRAMMING

BUILD IN FUNCTIONS IN PYTHON

The Python built-in functions are defined as the functions whose functionality is pre-
defined in Python. The python interpreter has several functions that are always present for use.
These functions are known as Built-in Functions. There are several built-in functions in Python
which are listed below:

print(): Prints the specified message to the console.


print("Hello, world!")
Output:
Hello, world!

input(): Prompts the user to input a value and returns it as a string.


name = input("Enter your name: ")
print("Hello, " + name + "!")
Output:
Enter your name: John Hello, John!

len(): Returns the length of the specified string, list, or tuple.


my_string = "Hello, world!"
print(len(my_string))
Output:
13

range(): Generates a sequence of numbers starting from 0 up to (but not including) the specified
number.
for i in range(5):
print(i)
Output:
01234

type(): Returns the data type of the specified variable.

UNIT III Page 3


CCS 62 – PYTHON PROGRAMMING

x=5
print(type(x))
y = "Hello, world!"
print(type(y))

Output:
<class 'int'> <class 'str'>

int(): Converts the specified string or float to an integer.

x = int("5")
print(x)
y = int(3.7)
print(y)

Output:
53

float(): Converts the specified string or integer to a float.


x = float("3.7")
print(x)
y = float(5)
print(y)

Output:
3.7 5.0

str(): Converts the specified variable to a string.


x=5
print("The value of x is " + str(x))

UNIT III Page 4


CCS 62 – PYTHON PROGRAMMING

Output:
The value of x is 5

list(): Converts the specified sequence (such as a string or tuple) to a list.


my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)

Output:
[1, 2, 3]

tuple(): Converts the specified sequence (such as a list or string) to a tuple.


my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)

Output:
(1, 2, 3)

FUNCTION DEFINITION AND CALLING IN PYTHON

Create a function in Python

To create a function, we need to use a def keyword to declare or write a function in


Python. Here is the syntax for creating a function:

Syntax

1. def function_name(): # use def keyword to define the function


2. Statement to be executed
3. return statement # return a single value.

Let's create a function program in Python.

UNIT III Page 5


CCS 62 – PYTHON PROGRAMMING

Myfun.py

1. def myFun(): # define function name


2. print(" Welcome to JavaTpoint")
3. myFun() # call to print the statement

Output:

Welcome to JavaTpoint

Function Calling in Python

Once a function is created in Python, we can call it by writing function_name() itself or


another function/ nested function. Following is the syntax for calling a function.

Syntax:

1. def function_name():
2. Statement1
3. function_name() # directly call the function
4. # calling function using built-in function
5. def function_name():
6. str = function_name('john') # assign the function to call the function
7. print(str) # print the statement

Consider the following example to print the Welcome Message using a function in Python.

CallFun.py

1. def MyFun():
2. print("Hello World")
3. print(" Welcome to the JavaTpoint")
4. MyFun() # Call Function to print the message.

Output:

Hello World
Welcome to the JavaTpoint

UNIT III Page 6


CCS 62 – PYTHON PROGRAMMING

In the above example, we call the MyFun() function that prints the statements.

Calling Nested Function in Python

When we construct one function inside another, it is called a nested function. We can
create nested functions using the def keyword. After creating the function, we have to call the
outer and the inner function to execute the statement. Lets' create a program to understand the
concept of nested functions and how we can call these functions.

Nest.py

1. def OutFun(): # outer function


2. print("Hello, it is the outer function")
3. def InFun(): # inner function
4. print("Hello, It is the inner function")
5. InFun() # call inner
6. OutFun() # call outer function

Output:

Hello, it is the outer function


Hello, it is the inner function

As we can see in the above example, the InFun() function is defined inside the OutFun()
function. To call the InFun() function, we first call the OutFun() function in the program. After
that, the OutFun() function will start executing and then call InFun() as the above output.

RETURN STATEMENT IN PYTHON

The Python return statement is used to return a value from a function. The user can only
use the return statement in a function. It cannot be used outside of the Python function. A return
statement includes the return keyword and the value that will be returned after that.

Syntax of return statement:

1. def funtion_name():
2. statements
3. .
4. .
5. .

UNIT III Page 7


CCS 62 – PYTHON PROGRAMMING

6. return [expression]

Here's a simple example that demonstrates the use of the return statement:

def multiply(a, b):


result = a * b
return result
print(multiply(2, 3)) # Output: 6

In this example, we define a function multiply that takes two arguments a and b. Inside
the function, we calculate the product of a and b and store it in a variable called result. We then
use the return statement to return result back to the calling statement.
When we call the multiply function with arguments 2 and 3, the function executes and
returns the result 6. This value is then printed to the console using the print statement.The
return statement can also be used to return multiple values, which are returned as a tuple.

Here's an example:
def calculate(a, b):
sum = a + b
difference = a - b
product = a * b
quotient = a / b
return sum, difference, product, quotient
result = calculate(10, 5)
print(result) # Output: (15, 5, 50, 2.0)

In this example, we define a function calculate that takes two arguments a and b. Inside
the function, we perform some arithmetic operations and store the results in variables sum,
difference, product, and quotient. We then use the return statement to return all these values
as a tuple.

UNIT III Page 8


CCS 62 – PYTHON PROGRAMMING

When we call the calculate function with arguments 10 and 5, the function executes and
returns a tuple containing the values 15, 5, 50, and 2.0. This tuple is then stored in the variable
result and printed to the console using the print statement.

VOID FUNCTION IN PYTHON

 Void function in Python is a function that performs an action but does not return any
computed or final value to the caller.
 It can accept any number of parameters and perform operation inside the function. A void
function may or may not return a value to the caller.
 If we do not declare return statement to return a value, Python will send a value None that
represents nothingness.
The following example code demonstrates the void function, which will calculate the sum of
two numbers and prints the result on the console.

Example 1:

# Python program demonstrates void function.


def voidOperation():
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
sum = num1 + num2
print('Sum of %d and %d = %d' %(num1, num2, sum))
def main_fn():
voidOperation() # calling one function from another function.
main_fn() # calling main function.

Output:
Enter your first number: 10
Enter your second number: 50
Sum of 10 and 50 = 60

Program explanation:

In the above program, we have declared a void function named voidOperation(), which
does not return any computed value but performs basic operation inside it.
Inside the void function, we have taken two numbers as inputs from the user. Then, we
have casted into int and stored them into two variables named num1 and num2, respectively.

UNIT III Page 9


CCS 62 – PYTHON PROGRAMMING

When we have called the void function voidOperation() from inside another function
main_fn(), the voidOperation() function performs the operation to calculate the sum of two
numbers and prints the result on the console.

SCOPE AND LIFETIME OF VARIABLES

In Python, the scope and lifetime of a variable determine when and where it can be
accessed or modified within a program.
A variable's scope defines the part of the program where it is visible and can be accessed.
A variable's lifetime refers to the period of time during which it exists in memory.
The lifetime of a variable in Python depends on the scope in which it is defined. When
the scope of a variable ends, the variable is removed from memory.
A variable is only available from inside the region it is created. This is called scope.

Local Scope

A variable created inside a function belongs to the local scope of that function, and can
only be used inside that function.

Example

A variable created inside a function is available inside that function:

def myfunc():
x = 300
print(x)
myfunc()

Function Inside Function

As explained in the example above, the variable x is not available outside the function,
but it is available for any function inside the function:

Example

The local variable can be accessed from a function within the function:

def myfunc():
x = 300

UNIT III Page 10


CCS 62 – PYTHON PROGRAMMING

def myinnerfunc():
print(x)
myinnerfunc()
myfunc()

Global Scope

A variable created in the main body of the Python code is a global variable and belongs
to the global scope.

Global variables are available from within any scope, global and local.

Example

A variable created outside of a function is global and can be used by anyone:

x = 300

def myfunc():
print(x)

myfunc()

print(x)

Naming Variables

If you operate with the same variable name inside and outside of a function, Python will
treat them as two separate variables, one available in the global scope (outside the function) and
one available in the local scope (inside the function):

Example

The function will print the local x, and then the code will print the global x:

x = 300

def myfunc():
x = 200

UNIT III Page 11


CCS 62 – PYTHON PROGRAMMING

print(x)

myfunc()

print(x)

Global Keyword

If you need to create a global variable, but are stuck in the local scope, you can use
the global keyword.

The global keyword makes the variable global.

Example

If you use the global keyword, the variable belongs to the global scope:

def myfunc():
global x
x = 300
myfunc()
print(x)

Also, use the global keyword if you want to make a change to a global variable inside a function.

Example

To change the value of a global variable inside a function, refer to the variable by using
the global keyword:

x = 300

def myfunc():
global x
x = 200

myfunc()

print(x)

UNIT III Page 12


CCS 62 – PYTHON PROGRAMMING

ARGS AND KWARGS IN PYTHON

In Python or any other programming language, we pass some variables or parameters to


some function. In this case, these variables are called arguments for the function. In the function
definition, we must define the type of arguments and the number of arguments we will pass.

But if we do not know the number of arguments we want to pass for any function, we can
use the *args and **kwargs keywords.

In other language, there is no flexibility to pass the variable number of arguments, but in Python,
we can pass the variable number of arguments in a function with the help of *args and **kwargs
keywords.

There are two types of arguments we can pass to a function:

1. Keyword arguments
2. Non-keyword arguments

If we want to pass the non-keyword arguments, we will use the *args keyword, and if we want to
pass the keyword arguments, we will use the **kwargs keyword.

Here * is termed as a wildcard where we can replace it with any number which signifies any
number of arguments in the function. The value of * can be zero, which means there will be no
argument in the function.

*args in Python

With this keyword, we can pass any variable length argument list to a function, and it is called
'args'. Since * represent variable number arguments so, it becomes iterable, which means we can
apply a loop on it or iterate it with any other function like map or filter.

Example1:

1. def multipleFunction(*argv):
2. for eachArg in argv:
3. print(eachArg)
4. multipleFunction('Hello', 'Welcome', 'to', 'Javatpoint')

UNIT III Page 13


CCS 62 – PYTHON PROGRAMMING

Output:

Explanation:

In the above code, we have one function which takes an argument as *argv, which simply means
we can pass any number of arguments as we want. Now in the function, we have applied for each
loop, we are printing every element of the loop.

So, we passed the four string arguments in the function, and we successfully printed it.

Example2:

We can pass the string as well as an integer data type with this keyword. So, there can be
arguments for different data types.

1. def multipleFunction(*argv):
2. for eachArg in argv:
3. print(eachArg)
4. multipleFunction('Hello', 'Welcome', 'to', 'Javatpoint',56,32)

Output:

Explanation:

In the above code, we have passed string and integer arguments and used the *argv keyword, and
we printed it using a for loop.

UNIT III Page 14


CCS 62 – PYTHON PROGRAMMING

**KWARGS IN PYTHON

This keyword is used when we pass the keyword arguments as the parameters for the
function. The keyword argument means that we pass the name to each variable, and this list is
stored as a dictionary of key-value pairs. The name of the variable is the key, and the value of the
variable is the value of the key.

Example1:

1. def multipleFunction(**kwargs):

2. for key, value in kwargs.items():

3. print("%s == %s" % (key, value))

4. multipleFunction(firstArg='Javat', Second='Point', Third='Ayush',Fourth = 6000)

Output:

Explanation:

In the above code, we have a function which takes arguments in the form **kwargs. The
arguments are stored as pairs of keys and values, so we passed four arguments with their name.
Now, if we iterate using the items() function of the keyword, we can print the key->value pair of
the variables.

Example 2:

1. def multipleFunction(*args,**kwargs):

2. print(args)

3. print(kwargs)

4. multipleFunction('helo','welcome','to',firstArg='Javat', Second='Point', Third='Ayush',Fourth =

6000)

UNIT III Page 15


CCS 62 – PYTHON PROGRAMMING

Output:

Explanation:

In the above code, we have used both *args and **kwargs keywords in a function, and
we have printed the whole argument. In the function call, we have passed some non-keyword
and then some keyword arguments. When we print the non-keyword argument, it is printed as a
list, and if we print the keyword argument, it is printed in the dictionary format of the key-value
pair.

COMMAND LINE ARGUMENTS IN PYTHON

In Python Command Line Arguments provides a convenient way to accept some


information at the command line while running the program. The arguments that are given after
the name of the Python script are known as Command Line Arguments and they are used to
pass some information to the program. For example -

$ python script.py arg1 arg2 arg3

Here Python script name is script.py and rest of the three arguments - arg1 arg2 arg3 are
command line arguments for the program. There are following three Python modules which are
helpful in parsing and managing the command line arguments:

1. sys module
2. getopt module
3. argparse module

sys module - System-specific parameters

The Python sys module provides access to any command-line arguments via the sys.argv.
This serves two purposes −

 sys.argv is the list of command-line arguments.


 len(sys.argv) is the number of command-line arguments.

Here sys.argv[0] is the program ie. script name.

Example

Consider the following script test.py −

import sys

UNIT III Page 16


CCS 62 – PYTHON PROGRAMMING

print 'Number of arguments:', len(sys.argv), 'arguments.'


print 'Argument List:', str(sys.argv)

Now run above script as below. All the programs in this tutorial need to be run from the
command line, so we are unable to provide online compile & run option for these programs.
Kindly try to run these programs at your computer.

$ python test.py arg1 arg2 arg3

This produce following result −

Number of arguments: 4 arguments.


Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

As mentioned above, first argument is always script name and it is also being counted in
number of arguments.

Parsing Command-Line Arguments

Python provided a getopt module that helps you parse command-line options and
arguments. This module provides two functions and an exception to enable command line
argument parsing.

getopt.getopt method

This method parses command line options and parameter list. Following is simple syntax
for this method −

getopt.getopt(args, options, [long_options])

Here is the detail of the parameters −

 args − This is the argument list to be parsed.


 options − This is the string of option letters that the script wants to recognize, with
options that require an argument should be followed by a colon (:).
 long_options − This is optional parameter and if specified, must be a list of strings with
the names of the long options, which should be supported. Long options, which require
an argument should be followed by an equal sign ('='). To accept only long options,
options should be an empty string.

This method getopt.getopt() returns value consisting of two elements: the first is a list of
(option, value) pairs. The second is the list of program arguments left after the option list was
stripped. Each option-and-value pair returned has the option as its first element, prefixed with a
hyphen for short options (e.g., '-x') or two hyphens for long options (e.g., '--long-option').

UNIT III Page 17


CCS 62 – PYTHON PROGRAMMING

Example

Following is a Python program which takes three arguments at command line:

1. First command line argument is -h which will be used to display the usage help of the
program.
2. Second argument is either -i or --ifile which we are considering as input file.
3. Third argument is either -o or --ofile which we are considering as output file.

Here is the following script to test.py −

import sys, getopt

def main(argv):
inputfile = ''
outputfile = ''
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
for opt, arg in opts:
if opt == '-h':
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print ('Input file is ', inputfile)
print ('Output file is ', outputfile)

if __name__ == "__main__":
main(sys.argv[1:])

Now, run above script as follows −

$ python test.py -i IN -o OUT

This will produce the following result:

Input file is IN
Output file is OUT

We can also run the above program as follows:

$ python test.py --ifile IN --ofile OUT

UNIT III Page 18


CCS 62 – PYTHON PROGRAMMING

This will produce the same result as in case of -i and -o:

Input file is IN
Output file is OUT

We can use h option to check the usage of the program:

$ python test.py -h

This will produce the following result:

test.py -i <inputfile> -o <outputfile>

Python argparse Module

Python argparse module makes it easy to write user-friendly command-line interfaces.


The program defines what arguments it requires, and argparse will figure out how to parse those
out of sys.argv. The argparse module also automatically generates help and usage messages. The
module will also issue errors when users give the program invalid arguments.

Example

Following is an example which makes simple use of argparse to accept a name parameter:<>/p>

import argparse

argParser = argparse.ArgumentParser()
argParser.add_argument("-n", "--name", help="your name")

args = argParser.parse_args()
print("args=%s" % args)

print("args.name=%s" % args.name)

You can add as many arguments as you like using add_argument() method, infact you can also
provide required data type of the argument as follows.

argParser.add_argument("-i", "--int", type=int, help="your numeric age ")

However, let's try to run above program as follows:

$ python test.py -h

This will display the following help:

usage: test.py [-h] [-n NAME]

UNIT III Page 19


CCS 62 – PYTHON PROGRAMMING

optional arguments:
-h, --help show this help message and exit
-n NAME, --name NAME your name

Now if we provide our name to the program as follows:

$ python test.py -n Zara

It will display following result:

args=Namespace(name='Zara')
args.name=Zara

TUPLES IN PYTHON

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

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

TUPLE CREATION IN PYTHON

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

UNIT III Page 20


CCS 62 – PYTHON PROGRAMMING

In Python, a tuple is a collection of ordered, immutable elements, enclosed in parentheses


(). Here are a few ways to create a tuple in Python:
Using parentheses:
my_tuple = (1, 2, 3, 4)
This creates a tuple named my_tuple with the elements 1, 2, 3, and 4.
Using the tuple() function:
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
This creates a tuple named my_tuple with the elements 1, 2, 3, and 4, by converting a list
my_list to a tuple using the tuple() function.
Creating a tuple with a single element:
my_tuple = (1,)
This creates a tuple named my_tuple with a single element, 1. Note that a trailing comma
is added after the element to indicate that it is a tuple.
Using unpacking to create a tuple:
a, b, c = 1, 2, 3
my_tuple = (a, b, c)
This creates a tuple named my_tuple with the elements 1, 2, and 3, by unpacking the variables a,
b, and c.
Creating an empty tuple:
my_tuple = ()
This creates an empty tuple named my_tuple.
Once created, the elements of a tuple cannot be modified. However, you can access and
use the elements of a tuple just like a list or any other sequence type in Python
Indexing in tuples is also pretty similar to that in lists, the first element has index zero,
and it keeps on increasing for the next consecutive elements. Also, backward indexing is also
valid in tuples, i.e., the last element can be accessed using the index -1 and the consecutive
previous numbers by -2, -3 and so on. Let's take an example,

>>> example = "apple", "orange", "banana", "berry", "mango"

>>> print (example[0]);

UNIT III Page 21


CCS 62 – PYTHON PROGRAMMING

In the table below we have marked the tuple elements for both forward and backward indexing:

Value Forward Indexing Backward Indexing

apple 0 -5

orange 1 -4

banana 2 -3

berry 3 -2

mango 4 -1

Adding Elements to a Tuple

As we know, that tuples are immutable, hence the data stored in a tuple cannot be edited, but it's
definitely possible to add more data to a tuple. This can be done using the addition operator.
Suppose there is a tuple,

>>> t = (1, 2, 3, 4, 5)

In case you want to add another element, 7 to the tuple, then you can do it as follows:

>>> t = t + (7,)

As you can see, we used the addition operator to add(7,) to the tuple t.

UNIT III Page 22


CCS 62 – PYTHON PROGRAMMING

>>> print (t);

(1, 2, 3, 4, 5, 7)

Hence, we can add any kind of element to a tuple, using the + operator.

If we try to think, what else can we do with the + operator, we might realize that it can be
used to combine two tuples as well. For example:

>>> print ((1, 2, 5, 8) + (2, 9, 4));

(1, 2, 5, 8, 2, 9, 4)

You can use a tuple(s) to create another tuple.

Deleting a Tuple

In order to delete a tuple, the del keyword is used. In order to delete a tuple
named myTuple(which we defined earlier), follow the example below:

>>> del (myTuple);

And myTuple will be deleted from the memory.

BASIC TUPLE OPERATIONS IN PYTHON

In Python, a tuple is an ordered and immutable sequence of elements, enclosed in


parentheses and separated by commas. Tuples are similar to lists, but unlike lists, tuples cannot
be modified once they are created. This means that you cannot add, remove or change elements
of a tuple after it has been created.

Some of the basic tuple operations in Python are:

Creating a tuple: A tuple can be created by enclosing a sequence of elements in parentheses and
separating them with commas.

For example:

UNIT III Page 23


CCS 62 – PYTHON PROGRAMMING

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

Accessing elements of a tuple: Elements of a tuple can be accessed using indexing, which starts
at 0. For example:

print(tup[0]) # Output: 1

print(tup[2]) # Output: 3

Slicing a tuple: A subset of elements of a tuple can be accessed using slicing, which is similar to
slicing a list.

For example:

print(tup[1:3]) # Output: (2, 3)

Concatenating tuples: Two or more tuples can be concatenated using the + operator.

For example:

tup1 = (1, 2, 3)

tup2 = (4, 5, 6)

tup3 = tup1 + tup2


print(tup3)

# Output: (1, 2, 3, 4, 5, 6)

Multiplying a tuple: A tuple can be multiplied by an integer to create a new tuple with repeated
elements.

For example:

tup1 = (1, 2, 3)
tup2 = tup1 * 3
print(tup2) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

Getting the length of a tuple: The length of a tuple can be obtained using the len() function.

For example:

print(len(tup)) # Output: 5

UNIT III Page 24


CCS 62 – PYTHON PROGRAMMING

Note that since tuples are immutable, operations like appending, removing, or changing
elements are not possible. If you need a mutable sequence of elements, you should use a list
instead.

TUPLE () FUNCTION IN PYTHON

The Python tuple() function is a built-in function in Python that can be used to create a
tuple. A tuple is an ordered and immutable sequence type.

Python tuple() Function Syntax

Syntax:

tuple(iterable)

 iterable (optional): It is an iterable(list, range etc..) or an iterator object


o If an iterable is passed, the corresponding tuple is created,
o else, an empty tuple is created.

Return: Returns a Tuple

It raises a TypeError, if an iterable is not passed. Below programs illustrate tuple()


function in Python.

Python tuple() Function Example:

l = [1,2,3]

print(tuple(l))

Output:

(1, 2, 3)

Example 1: Uses of tuple() in Python

Program demonstrating the use of tuple() function.

# when parameter is not passed

tuple1 = tuple()

print("empty tuple:", tuple1)

# when an iterable(e.g., list) is passed

UNIT III Page 25


CCS 62 – PYTHON PROGRAMMING

list1= [ 1, 2, 3, 4 ]

tuple2 = tuple(list1)

print("list to tuple:", tuple2)

# when an iterable(e.g., dictionary) is passed

dict = { 1 : 'one', 2 : 'two' }

tuple3 = tuple(dict)

print("dict to tuple:", tuple3)

# when an iterable(e.g., string) is passed

string = "geeksforgeeks";

tuple4 = tuple(string)

print("str to tuple:", tuple4)

Output:

empty tuple: ()
list to tuple: (1, 2, 3, 4)
dict to tuple: (1, 2)
str to tuple: ('g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's')

Example 2: Errors when using Tuple

Program demonstrating the TypeError using tuple()

# Python3 program demonstrating

# the TypeError in tuple() function

# Error when a non-iterable is passed

tuple1 = tuple(1)

print(tuple1)

Output:

Traceback (most recent call last):

UNIT III Page 26


CCS 62 – PYTHON PROGRAMMING

File "/home/eaf759787ade3942e8b9b436d6c60ab3.py", line 5, in


tuple1=tuple(1)
TypeError: 'int' object is not iterable

INDEXING IN PYTHON

In Python, indexing refers to accessing individual elements or groups of elements within


a sequence, such as a string, list, or tuple. Indexing allows you to retrieve specific elements from
a sequence by referring to their position within the sequence.

The syntax for indexing in Python is square brackets, [], which follow the name of the
sequence you want to access. Inside the brackets, you specify the index or indices of the element
or elements you want to retrieve.

Here's an example of indexing a string:

my_string = "Hello, World!"


print(my_string[0]) # Output: "H"
print(my_string[7]) # Output: "W"
print(my_string[3:7]) # Output: "lo, "

In the first example, we retrieve the first character of the string by using an index of 0. In
the second example, we retrieve the eighth character of the string by using an index of 7. In the
third example, we retrieve a substring from the fourth character up to, but not including, the
eighth character by using a slice with the range of 3:7.

Indexing can also be used with lists and tuples in a similar way.

In Python, a tuple is an ordered collection of elements, similar to a list, but tuples are
immutable. This means that once a tuple is created, its elements cannot be modified.

To access individual elements or groups of elements within a tuple, you can use indexing.
The syntax for indexing a tuple is the same as for indexing a list or a string. You use square
brackets, [], with the index or indices of the element(s) you want to access.

Here is an example:

my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: 3
print(my_tuple[1:4]) # Output: (2, 3, 4)

In the first example, we retrieve the first element of the tuple, which is 1, using an index
of 0. In the second example, we retrieve the third element of the tuple, which is 3, using an index
of 2. In the third example, we retrieve a slice of the tuple, starting from the second element up to,
but not including, the fifth element.

UNIT III Page 27


CCS 62 – PYTHON PROGRAMMING

Tuples are immutable, you cannot modify their elements directly. If you want to modify a
tuple, you must create a new tuple with the desired elements.

SLICING IN PYTHON

In Python, slicing refers to extracting a subset of elements from a sequence, such as a


string, list, or tuple. Slicing allows you to create a new sequence containing a subset of the
original sequence's elements.

The syntax for slicing in Python is to use square brackets, [], with two indices separated
by a colon, ":". The first index specifies the starting position of the slice, and the second index
specifies the ending position of the slice (not including the element at that position).

Here's an example of slicing a string:

my_string = "Hello, World!"


print(my_string[0:5]) # Output: "Hello"
print(my_string[7:12]) # Output: "World"
print(my_string[3:]) # Output: "lo, World!"

In the first example, we slice the string to retrieve the first five characters. In the second
example, we slice the string to retrieve the five characters from index 7 to index 11. In the third
example, we slice the string to retrieve all the characters from index 3 to the end of the string.

You can also specify a step value for the slice, which determines the increment between
the indices. The default step value is 1. Here's an example:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[1:8:2]) # Output: [2, 4, 6, 8]

In this example, we slice the list to retrieve a subset of elements, starting with the second
element (index 1) up to, but not including, the eighth element (index 7), with a step value of 2,
which means we only retrieve every second element.

Note that slicing in Python creates a new sequence with the specified subset of elements.
The original sequence is not modified.

In Python, a tuple is an ordered collection of elements, similar to a list, but tuples are
immutable. To access a subset of elements within a tuple, you can use slicing.

The syntax for slicing a tuple is similar to the syntax for slicing a list or a string. You use
square brackets, [], with two indices separated by a colon, ":". The first index specifies the
starting position of the slice, and the second index specifies the ending position of the slice (not
including the element at that position).

Here is an example:

UNIT III Page 28


CCS 62 – PYTHON PROGRAMMING

my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)

In this example, we slice the tuple to retrieve a subset of elements, starting with the
second element (index 1) up to, but not including, the fifth element (index 4).

You can also specify a step value for the slice, which determines the increment between
the indices. The default step value is 1. Here is an example:

my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0:5:2]) # Output: (1, 3, 5)

In this example, we slice the tuple to retrieve a subset of elements, starting with the first
element (index 0) up to, but not including, the fifth element (index 4), with a step value of 2,
which means we only retrieve every second element.

Note that, because tuples are immutable, slicing a tuple creates a new tuple with the
specified subset of elements.

BUILT IN FUNCTIONS OF TUPLES

Python provides the following built-in functions which can be used with the tuples.

 len()
 max()
 min()
 tuple()
 sum()
 sorted()
 index()
 count()

☞ len()

In Python len() is used to find the length of tuple,i.e it returns the number of items in the tuple.
Syntax:

len(tuple)

Example:

UNIT III Page 29


CCS 62 – PYTHON PROGRAMMING

num=(1,2,3,4,5,6)
print(“length of tuple :”,len(num))

Output:
length of tuple : 6

☞ max()

In Python max() is used to find maximum value in the tuple.


Syntax:

max(tuple)

Example:
num=(1,2,3,4,5,6)
lang=('java','c','python','cpp')
print("Max of tuple :",max(num))
print("Max of tuple :",max(lang))

Output:
Max of tuple : 6
Max of tuple : python

☞ min()

In Python min() is used to find minimum value in the tuple.


Syntax:

min(tuple)

Example:
num=(1,2,3,4,5,6)
lang=('java','c','python','cpp')
print("Min of tuple :",min(num))
print("Min of tuple :",min(lang))

UNIT III Page 30


CCS 62 – PYTHON PROGRAMMING

Output:
Min of tuple: 1
Min of tuple : c

☞ sum()

In python, sum(tuple) function returns sum of all values in the tuple. Tuple values must in
number type.
Syntax:

sum(tuple)

Example:
num=(1,2,3,4,5,6)
print(“sum of tuple items :”,sum(num))

Output:
sum of tuple items: 21

☞ sorted()

In python, sorted (tuple) function is used to sort all items of tuple in an ascending order. It also
sorts the items into descending and ascending order. It takes an optional parameter 'reverse'
which sorts the tuple into descending order.
Syntax:

sorted (tuple[,reverse=True])

Example:
num=(1,3,2,4,6,5)
lang=('java','c','python','cpp')
print(sorted(num))
print(sorted(lang))
print(sorted(num,reverse=True))

Output:
(1, 2, 3, 4, 5, 6)
UNIT III Page 31
CCS 62 – PYTHON PROGRAMMING

('c', 'cpp', 'java', 'python')


(6, 5, 4, 3, 2, 1)

☞ tuple (sequence)

The tuple() method takes sequence types and converts them to tuples. This is used to convert a
given string or list into tuple.
Syntax:

tuple(sequence)

Example:
str="python"
tuple1=tuple(str)
print(tuple1)
num=[1,2,3,4,5,6]
tuple2=tuple(num)
print(tuple2)

Output:
('p', 'y', 't', 'h', 'o', 'n')
(1, 2, 3, 4, 5, 6)

☞ count()

In python count() method returns the number of times element appears in the tuple. If the
element is not present in the tuple, it returns 0.
Syntax:

tuple.count (item)

Example:
num=(1,2,3,4,3,2,2,1,3,4,5,7,8)
cnt=num.count(2)
print("Count of 2 is:",cnt)
cnt=num.count(10)
print("Count of 10 is:",cnt)

UNIT III Page 32


CCS 62 – PYTHON PROGRAMMING

Output:
Count of 2 is: 3
Count of 10 is : 0

☞ index()

In python index () method returns index of the passed element. This method takes an argument
and returns index of it. If the element is not present, it raises a ValueError.

If tuple contains duplicate elements, it returns index of first occurred element.


This method takes two more optional parameters start and end which are used to search index
within a limit.
Syntax:

tuple.index(x[, start[, end]])

Example:
lang = ('p', 'y', 't', 'h', 'o','n','p','r','o','g','r','a','m')
print("index of t is:",lang.index('t'))
print("index of p is:",lang.index('p'))
print("index of p is:",lang.index('p',3,10))
print("index of p is:",lang.index('z'))

Output:
index of t is: 2
index of p is: 0
index of p is: 6
ValueError: 'z' is not in tuple.

TUPLE METHODS IN PYTHON

UNIT III Page 33


CCS 62 – PYTHON PROGRAMMING

In Python, tuples are immutable objects, which means once created, their contents cannot
be modified. As a result, tuple objects have a limited number of methods. Here are some of the
methods available for tuples in Python:

Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in a tuple

Searches the tuple for a specified value and returns the position of where it
index()
was found

1. count(x) - This method returns the number of times a specified value, 'x', occurs in the
tuple. Example:

scss
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.count(2)) # Output: 3

2. index(x) - This method returns the index of the first occurrence of a specified value, 'x', in
the tuple. If the value is not found, it raises a ValueError. Example:

scss
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.index(2)) # Output: 1

Note that both count() and index() methods are read-only and do not modify the tuple.

In addition to these methods, tuple objects also have access to some built-in functions in
Python, such as len(), max(), min(), and sorted(). These functions can be used with tuple objects
just as they can be used with lists and other iterable objects in Python.

Since tuples are immutable, they don't have methods for adding, removing or modifying
elements like lists do. However, you can concatenate two tuples using the '+' operator to create a
new tuple with the combined elements.

PACKING OF TUPLES

When we create a tuple, we normally assign values to it. This is called "packing" a tuple:

Example

Packing a tuple:

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

UNIT III Page 34


CCS 62 – PYTHON PROGRAMMING

But, in Python, we are also allowed to extract the values back into variables. This is
called "unpacking":

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:

Example

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)

If the asterisk is added to another variable name than the last, Python will assign values to
the variable until the number of values left matches the number of variables left.

Example

Add a list of values the "tropic" variable:

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits

print(green)

UNIT III Page 35


CCS 62 – PYTHON PROGRAMMING

print(tropic)
print(red)

UNPACKING OF TUPLES

A tuple is an ordered, immutable sequence of elements, typically used to group related


data together. You can define a tuple in Python using parentheses () and separating the values
with commas ,. For example:

my_tuple = (1, 2, 3)

To unpack the values in a tuple, you simply need to assign the tuple to a comma-
separated list of variables:

a, b, c = my_tuple

This line of code unpacks the tuple my_tuple and assigns the first element to the variable
a, the second element to the variable b, and the third element to the variable c. You can then use
these variables later in your code:

python
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3

One important thing to note is that the number of variables on the left-hand side of the
assignment operator (=) must match the number of elements in the tuple. If you have more
variables than elements in the tuple, you will get a ValueError. If you have fewer variables, you
will get a TypeError.

# ValueError - too many variables


a, b, c, d = my_tuple # Raises ValueError: "too many values to unpack"

# TypeError - not enough variables


a, b = my_tuple # Raises TypeError: "not enough values to unpack"

If you want to ignore certain elements in the tuple, you can use the underscore (_) as a
placeholder. For example:

UNIT III Page 36


CCS 62 – PYTHON PROGRAMMING

# Ignore the second element


a, _, c = my_tuple
print(a) # Output: 1
print(c) # Output: 3

You can also use the * operator to assign the remaining elements of a tuple to a single
variable:

# Assign the first element to a and the remaining elements to b


a, *b = my_tuple
print(a) # Output: 1
print(b) # Output: [2, 3]

Here, the *b syntax assigns the remaining elements of my_tuple to the variable b as a list.

Unpacking of tuples is a useful technique in Python that can simplify your code and make
it more readable.

TRAVERSING OF TUPLES

Traversing a tuple in Python means iterating over all the elements of the tuple and
performing some operation on each element. Tuples are immutable and ordered collections of
elements, which can be of any type. Here are some examples of how to traverse tuples in Python:
Using a for loop:
You can use a for loop to iterate over the elements in a tuple. For example:
my_tuple = (10, 20, 30, 40, 50)
for item in my_tuple:
print(item)

Using indexing:
You can access the elements in a tuple using their index. For example:
my_tuple = ('apple', 'banana', 'cherry', 'date')
for i in range(len(my_tuple)):
print(my_tuple[i])

UNIT III Page 37


CCS 62 – PYTHON PROGRAMMING

OUTPUT :

Using the enumerate function:


The enumerate function can be used to iterate over the elements in a tuple and their indices at the
same time. For example:
my_tuple = ('red', 'green', 'blue', 'yellow')
for i, item in enumerate(my_tuple):
print(i, item)

OUTPUT :

Using a while loop:


You can use a while loop to iterate over the elements in a tuple. For example:

my_tuple = ('John', 'Doe', 25)


i=0
while i < len(my_tuple):
print(my_tuple[i])
i += 1

OUTPUT :

UNIT III Page 38


CCS 62 – PYTHON PROGRAMMING

POPULATING TUPLES
Tuples in Python are immutable, meaning that once they are created, their contents
cannot be changed. However, there are situations when we want to change the existing tuple, in
which case we must make a new tuple using only the changed elements from the original tuple.
Following is the example of the tuple −

s = (4,5,6)

print(s)

print(type(s))
Following is the output of the above code −
(4, 5, 6)
<class 'tuple'>
Tuple is immutable, although you can use the + operator to concatenate several tuples.
The old object is still present at this point, and a new object is created.

Append elements in Tuple

Tuple is immutable, although you can use the + operator to concatenate several tuples.
The old object is still present at this point, and a new object is created.

Example
Following is an example to append the tuple −

s=(2,5,8)

s_append = s + (8, 16, 67)

print(s_append)

print(s)

Output
Following is an output of the above code −

UNIT III Page 39


CCS 62 – PYTHON PROGRAMMING

(2, 5, 8, 8, 16, 67)


(2, 5, 8)

Note− Concatenation is only possible with tuples. It can't be concatenated to other kinds, such
lists.
Example
Following is an example of concatenating a tuple with a list −

s=(2,5,8)

s_append = (s + [8, 16, 67])

print(s_append)

print(s)

Output
The following error came as an output of the above code −
Traceback (most recent call last):
File "main.py", line 2, in <module>
s_append = (s + [8, 16, 67])
TypeError: can only concatenate tuple (not "list") to tuple

Concatenating Tuple with one element

You can concatenate a tuple with one element if you want to add an item to it.
Example
Following is an example to concatenate a tuple with one element −

s=(2,5,8)

s_append_one = s + (4,)

print(s_append_one)

Output
Following is an output of the above code.
(2, 5, 8, 4)

UNIT III Page 40


CCS 62 – PYTHON PROGRAMMING

Note − The end of a tuple with only one element must contain a comma as seen in the above
example.
Adding/Inserting items in a Tuple

You can concatenate a tuple by adding new items to the beginning or end as previously
mentioned; but, if you wish to insert a new item at any location, you must convert the tuple to a
list.
Example
Following is an example of adding items in tuple −

s= (2,5,8)

# Python conversion for list and tuple to one another

x = list(s)

print(x)

print(type(x))

# Add items by using insert ()

x.insert(5, 90)

print(x)

# Use tuple to convert a list to a tuple ().

s_insert = tuple(x)

print(s_insert)

print(type(s_insert))

Output
we get the following output of the above code.
[2, 5, 8]
⁢class 'list'>
[2, 5, 8, 90]
(2, 5, 8, 90)
⁢class 'tuple'>

Using append() method

UNIT III Page 41


CCS 62 – PYTHON PROGRAMMING

A new element is added to the end of the list using the append() method.
Example
Following is an example to append an element using append() method −

# converting tuple to list

t=(45,67,36,85,32)

l = list(t)

print(l)

print(type(l))

# appending the element in a list

l.append(787)

print(l)

# Converting the list to tuple using tuple()

t=tuple(l)

print(t)

Output
Following is an output of the above code
[45, 67, 36, 85, 32]
⁢class 'list'>
[45, 67, 36, 85, 32, 787]
(45, 67, 36, 85, 32, 787)

ZIP FUNCTION

Definition and Usage

UNIT III Page 42


CCS 62 – PYTHON PROGRAMMING

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.

Syntax

zip(iterator1, iterator2, iterator3 ...)

Parameter Values

Parameter Description

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


joined together

a = ("John", "Charles", "Mike")


b = ("Jenny", "Christy", "Monica")

x = zip(a, b)

#use the tuple() function to display a readable version of the result:

print(tuple(x))

More Examples

UNIT III Page 43


CCS 62 – PYTHON PROGRAMMING

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

a = ("John", "Charles", "Mike")


b = ("Jenny", "Christy", "Monica", "Vicky")

x = zip(a, b)

Python zip() method takes iterable or containers and returns a single iterator object, having
mapped values from all the containers.

It is used to map the similar index of multiple containers so that they can be used just
using a single entity.

Syntax : zip(*iterators)

Parameters : Python iterables or containers ( list, string etc )

Return Value : Returns a single iterator object, having mapped values from all the
containers.

Python zip() example

Example 1: Python zip two lists

name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ]


roll_no = [ 4, 1, 3, 2 ]

# using zip() to map values


mapped = zip(name, roll_no)

print(set(mapped))

Output:
{('Shambhavi', 3), ('Nikhil', 1), ('Astha', 2), ('Manjeet', 4)}

Example 2: Python zip enumerate

UNIT III Page 44


CCS 62 – PYTHON PROGRAMMING

names = ['Mukesh', 'Roni', 'Chari']


ages = [24, 50, 18]

for i, (name, age) in enumerate(zip(names, ages)):


print(i, name, age)

Output:
0 Mukesh 24
1 Roni 50
2 Chari 18

Example 3: Python zip() Dictionary

stocks = ['reliance', 'infosys', 'tcs']


prices = [2175, 1127, 2750]

new_dict = {stocks: prices for stocks,


prices in zip(stocks, prices)}
print(new_dict)

Output:
{'reliance': 2175, 'infosys': 1127, 'tcs': 2750}

How to unzip?
Unzipping means converting the zipped values back to the individual self as they were.
This is done with the help of “*” operator.

# Python code to demonstrate the working of


# unzip
# initializing lists
name = ["Manjeet", "Nikhil", "Shambhavi", "Astha"]
roll_no = [4, 1, 3, 2]
marks = [40, 50, 60, 70]

# using zip() to map values


mapped = zip(name, roll_no, marks)

# converting values to print as list


mapped = list(mapped)

# printing resultant values


print("The zipped result is : ", end="")

UNIT III Page 45


CCS 62 – PYTHON PROGRAMMING

print(mapped)

print("\n")

# unzipping values
namz, roll_noz, marksz = zip(*mapped)

print("The unzipped result: \n", end="")

# printing initial lists


print("The name list is : ", end="")
print(namz)

print("The roll_no list is : ", end="")


print(roll_noz)

print("The marks list is : ", end="")


print(marksz)

Output:
The zipped result is : [('Manjeet', 4, 40), ('Nikhil', 1, 50),
('Shambhavi', 3, 60), ('Astha', 2, 70)]
The unzipped result:
The name list is : ('Manjeet', 'Nikhil', 'Shambhavi', 'Astha')
The roll_no list is : (4, 1, 3, 2)
The marks list is : (40, 50, 60, 70)
myset = {"apple", "banana", "cherry"}

SETS IN PYTHON

Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

Set items are unchangeable, but you can remove items and add new items.

Sets are written with curly brackets.

Example

Create a Set:

UNIT III Page 46


CCS 62 – PYTHON PROGRAMMING

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


print(thisset)

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered

Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has
been created.

Once a set is created, you cannot change its items, but you can remove items and add new items.

Duplicates Not Allowed

Sets cannot have two items with the same value.

Example

Duplicate values will be ignored:

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

print(thisset)

OUTPUT :

The values True and 1 are considered the same value in sets, and are treated as duplicates:

UNIT III Page 47


CCS 62 – PYTHON PROGRAMMING

Example

True and 1 is considered the same value:

thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)

OUTPUT :

Get the Length of a Set

To determine how many items a set has, use the len() function.

Example

Get the number of items in a set:

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

print(len(thisset))

OUTPUT :

Set Items - Data Types

Set items can be of any data type:

Example

String, int and boolean data types:

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


set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

UNIT III Page 48


CCS 62 – PYTHON PROGRAMMING

OUTPUT :

A set can contain different data types:

Example

A set with strings, integers and boolean values:

set1 = {"abc", 34, True, 40, "male"}

OUTPUT :

type()

From Python's perspective, sets are defined as objects with the data type 'set':

<class 'set'>

Example

What is the data type of a set?

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


print(type(myset))

OUTPUT :

The set() Constructor

It is also possible to use the set() constructor to make a set.

UNIT III Page 49


CCS 62 – PYTHON PROGRAMMING

Example

Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets


print(thisset)

OUTPUT :

TRAVERSING OF SETS IN PYTHON

Sets are an unordered collection, and so the items cannot be accessed through indexing. If we
want to access the set items, we will have to iterate with the help of loop statements. Some of the
ways to iterate through set in python are:

1. Using for loop statement


2. Enumerating over a set
3. Using iter with for loop
4. Converting the set to a list
5. Using comprehension
6. Iterating over two sets simultaneously using zip()

Using for loop statement

The simplest way of iterating through a set is using the for loop statement. Let us consider a set
named ‘my_set’ containing names of five different cities.
1 my_set = {'london', 'new york', 'seattle', 'sydney','chicago'}

Now, if we want to access each set element, then we can do that by printing the set element wise
using for loop.

1 for item in my_set:

2 print(item)

The output of the code is:


london

seattle

new york

UNIT III Page 50


CCS 62 – PYTHON PROGRAMMING

chicago

sydney

The entire code is:

1 my_set = {'london', 'new york', 'seattle', 'sydney','chicago'}


2 for item in my_set:
3 print(item)

2. Enumerating over a set

We can also use enumerated for loop for iterating over python sets. When we
use enumerate() method, we receive a counter along with the iterable item.

my_set = {'london', 'new york', 'seattle', 'sydney','chicago'}


1 for counter, item in enumerate(my_set):
2 print(item)
3

As the output, we will print the iterable item.

london

seattle

new york

chicago

sydney

You can also print the counter along with the iterable item. For that, we shall print the variable
„counter„ along with ‘item’.

The code is:

UNIT III Page 51


CCS 62 – PYTHON PROGRAMMING

my_set = {'london', 'new york', 'seattle',


1
'sydney','chicago'}
2
for counter, item in enumerate(my_set):
3
print(counter,":",item)

The output of the code is:

0 : london

1 : seattle

2 : new york

3 : chicago

4 : sydney

3. Using iter with for loop

We can use the iter() method as well for iterating through a python set. The iter() method will
return an iterator. Using that iterator, we can iterate over a given object. We shall use
the iter() method with a for loop.

1 my_set = {'london', 'new york', 'seattle', 'sydney','chicago'}

2 for item in iter(my_set):

3 print(item)

The output is:


london

seattle

new york

chicago

Sydney

4. Converting the set to a list

UNIT III Page 52


CCS 62 – PYTHON PROGRAMMING

We can also convert a set explicitly to a list in order to iterate over it. We shall take the same list
as before:

1 my_set = {'london', 'new york', 'seattle', 'sydney','chicago'}

Now, we shall convert the ‘my_set’ set to a list using list() and store that list into a variable
named ‘my_list’.

1 my_list = list(my_set)

Then, we can iterate over that list using indexing.

1 for i in range(0,len(my_list)):

2 print(my_list[i])

The output is:

london

seattle

new york

chicago

sydney

Instead of a for loop statement, we can also use a while loop. We take a counter
variable ‘i’, which is initially equal to zero. Then, we can check in the while loop condition that
the counter ‘i’ should be less than the length of ‘my_list’. We will print each list item using
indexing and increment the variable ‘i’ every time.

1 i=0

2 while i < len(my_list):

3 print(my_list[i])

4 i=i+1

Output:
london

UNIT III Page 53


CCS 62 – PYTHON PROGRAMMING

seattle

new york

chicago

sydney

5. Using comprehension

Comprehension in python is a compact piece of code used to generate new sequences from
already existing sequences. Comprehension consists of three main parts – the expression to be
printed, the iterable item, and the list, which is the sequence. Here, we shall generate a sequence
of items from the existing set my_set.

The syntax for list comprehension is:

[expression for item in list]

1 my_set = {'london', 'new york', 'seattle', 'sydney','chicago'}


2 val = [print(item) for item in my_set]

The output of the code is:


london

seattle

new york

chicago

sydney

6. Iterating over two sets simultaneously using zip()

We can also iterate over two sets in python using the zip() function. The zip function
returns a zip object. With that, we can iterate over two or more iterables simultaneously. This
saves a lot of computation time because multiple sequences are iterated simultaneously.

UNIT III Page 54


CCS 62 – PYTHON PROGRAMMING

We shall take the following two sets – ‘set1’ and ‘set2’.

1 set1 = {10, 20, 30, 40, 50}

2 set2 = {100, 200, 300, 400, 500}

Using the zip() function, we shall create two iterables for each set – ‘i1’ and ‘i2’. Then, we shall
print i1 and i2.

1 for (i1, i2) in zip(set1, set2):

2 print(i1, i2)

The output is:

40 100

10 200

50 300

20 400

30 500

SET METHODS IN PYTHON

In Python, a set is an unordered collection of unique elements. A set can be created by


enclosing a comma-separated list of elements in curly braces {} or by using the set() function.

Python provides a number of built-in methods that can be used to manipulate sets. Here
are some of the most commonly used set methods:

Here are some of the most commonly used set methods in Python:

add(): Adds an element to a set.


my_set = {1, 2, 3}
my_set.add(4)
print(my_set)

# Output: {1, 2, 3, 4}

UNIT III Page 55


CCS 62 – PYTHON PROGRAMMING

update(): Adds elements from another iterable (such as a list or another set) to a set.

my_set = {1, 2, 3} my_set.update([3, 4, 5]) print(my_set)

# Output: {1, 2, 3, 4, 5}

remove(): Removes an element from a 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}

discard(): Removes an element from a set if it is a member. If the element is not a member, no
error is raised.

my_set = {1, 2, 3} my_set.discard(2)


print(my_set)

# Output: {1, 3}
pop(): Removes and returns an arbitrary element from a set. Raises a KeyError if the set is
empty.

my_set = {1, 2, 3}
element = my_set.pop() print(element) # Output: 1 print(my_set) # Output: {2, 3}

clear(): Removes all elements from a set.

my_set = {1, 2, 3}
my_set.clear()
print(my_set)

# Output: set()
union(): Returns a new set containing all elements from two or more sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) print(union_set)

# Output: {1, 2, 3, 4, 5}

intersection(): Returns a new set containing only the elements that are common to two or more
sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}

UNIT III Page 56


CCS 62 – PYTHON PROGRAMMING

intersection_set = set1.intersection(set2) print(intersection_set)

# Output: {3}

difference(): Returns a new set containing only the elements that are in one set but not in
another.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2) print(difference_set)

# Output: {1, 2}

symmetric_difference(): Returns a new set containing only the elements that are in either of two
sets, but not in both.

set1 = {1, 2, 3}
set2 = {3, 4, 5} symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)
# Output: {1, 2, 4, 5}

FROZEN SETS IN PYTHON

Python frozenset() Method creates an immutable Set object from an iterable. It is a


built-in Python function. As it is a set object therefore we cannot have duplicate values in the
frozenset.

frozenset() in Python

Syntax : frozenset(iterable_object_name)
Parameter : iterable_object_name
This function accepts iterable object as input parameter.
Return : Returns an equivalent frozenset object.

Using frozenset() Method on tuple

If no parameters are passed to frozenset() function, then it returns an empty frozenset


type object in Python.

# passing an empty tuple


nu = ()

# converting tuple to frozenset


fnum = frozenset(nu)

UNIT III Page 57


CCS 62 – PYTHON PROGRAMMING

# printing empty frozenset object


print("frozenset Object is : ", fnum)

Output:

frozenset Object is : frozenset()


Using frozenset() Method on list
Here as a parameter a list is passed and now it‟s frozenset object is returned.

l = ["Geeks", "for", "Geeks"]

# converting list to frozenset


fnum = frozenset(l)

# printing empty frozenset object


print("frozenset Object is : ", fnum)

Output:
frozenset Object is : frozenset({'Geeks', 'for'})

Using frozenset() Method on Dictionary

Since frozenset objects are immutable, they are mainly used as key in dictionary or elements of
other sets. The below example explains it clearly.

# creating a dictionary
Student = {"name": "Ankit", "age": 21, "sex": "Male",
"college": "MNNIT Allahabad", "address": "Allahabad"}

# making keys of dictionary as frozenset


key = frozenset(Student)

# printing dict keys as frozenset


print('The frozen set is:', key)

Output:

The frozen set is: frozenset({'address', 'name', 'age', 'sex', 'college'})


Exceptions while using Python frozenset() method

If by mistake we want to change the frozenset object, then it throws a TypeError

UNIT III Page 58


CCS 62 – PYTHON PROGRAMMING

Python3

# creating a list
favourite_subject = ["OS", "DBMS", "Algo"]

# creating a frozenset
f_subject = frozenset(favourite_subject)

# below line will generate error


f_subject[1] = "Networking"

Output:

TypeError
Traceback (most recent call last)
Input In [13], in <cell line: 8>()
5 f_subject = frozenset(favourite_subject)
7 # below line will generate error
----> 8 f_subject[1] = "Networking"

TypeError: 'frozenset' object does not support item assignment

UNIT III Page 59

You might also like