Unit Iii Python
Unit Iii Python
UNIT III
FUNCTIONS IN PYTHON
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.
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.
Creating a Function
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.
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.
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:
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
x=5
print(type(x))
y = "Hello, world!"
print(type(y))
Output:
<class 'int'> <class 'str'>
x = int("5")
print(x)
y = int(3.7)
print(y)
Output:
53
Output:
3.7 5.0
Output:
The value of x is 5
Output:
[1, 2, 3]
Output:
(1, 2, 3)
Syntax
Myfun.py
Output:
Welcome to JavaTpoint
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
In the above example, we call the MyFun() function that prints the statements.
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
Output:
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.
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.
1. def funtion_name():
2. statements
3. .
4. .
5. .
6. return [expression]
Here's a simple example that demonstrates the use of the return statement:
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.
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 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:
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.
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.
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
def myfunc():
x = 300
print(x)
myfunc()
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
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
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
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.
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)
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.
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')
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.
**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):
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)
6000)
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.
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
The Python sys module provides access to any command-line arguments via the sys.argv.
This serves two purposes −
Example
import sys
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.
As mentioned above, first argument is always script name and it is also being counted in
number of 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 −
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').
Example
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.
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:])
Input file is IN
Output file is OUT
Input file is IN
Output file is OUT
$ python test.py -h
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.
$ python test.py -h
optional arguments:
-h, --help show this help message and exit
-n NAME, --name NAME your name
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
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.
A tuple can contain any number of items, including ones with different data
types (dictionary, string, float, list, etc.).
In the table below we have marked the tuple elements for both forward and backward indexing:
apple 0 -5
orange 1 -4
banana 2 -3
berry 3 -2
mango 4 -1
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.
(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:
(1, 2, 5, 8, 2, 9, 4)
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:
Creating a tuple: A tuple can be created by enclosing a sequence of elements in parentheses and
separating them with commas.
For example:
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:
Concatenating tuples: Two or more tuples can be concatenated using the + operator.
For example:
tup1 = (1, 2, 3)
tup2 = (4, 5, 6)
# 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
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.
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.
Syntax:
tuple(iterable)
l = [1,2,3]
print(tuple(l))
Output:
(1, 2, 3)
tuple1 = tuple()
list1= [ 1, 2, 3, 4 ]
tuple2 = tuple(list1)
tuple3 = tuple(dict)
string = "geeksforgeeks";
tuple4 = tuple(string)
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')
tuple1 = tuple(1)
print(tuple1)
Output:
INDEXING IN PYTHON
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.
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.
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
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).
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:
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.
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:
num=(1,2,3,4,5,6)
print(“length of tuple :”,len(num))
Output:
length of tuple : 6
☞ max()
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()
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))
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
☞ 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)
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.
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.
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
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:
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
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
print(green)
print(tropic)
print(red)
UNPACKING OF TUPLES
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.
If you want to ignore certain elements in the tuple, you can use the underscore (_) as a
placeholder. For example:
You can also use the * operator to assign the remaining elements of a tuple to a single
variable:
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])
OUTPUT :
OUTPUT :
OUTPUT :
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.
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)
print(s_append)
print(s)
Output
Following is an output of the above code −
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)
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
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)
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)
x = list(s)
print(x)
print(type(x))
x.insert(5, 90)
print(x)
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'>
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 −
t=(45,67,36,85,32)
l = list(t)
print(l)
print(type(l))
l.append(787)
print(l)
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
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
Parameter Values
Parameter Description
x = zip(a, b)
print(tuple(x))
More Examples
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)
Return Value : Returns a single iterator object, having mapped values from all the
containers.
print(set(mapped))
Output:
{('Shambhavi', 3), ('Nikhil', 1), ('Astha', 2), ('Manjeet', 4)}
Output:
0 Mukesh 24
1 Roni 50
2 Chari 18
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.
print(mapped)
print("\n")
# unzipping values
namz, roll_noz, marksz = zip(*mapped)
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
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.
Set items are unchangeable, but you can remove items and add new items.
Example
Create a Set:
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.
Example
print(thisset)
OUTPUT :
The values True and 1 are considered the same value in sets, and are treated as duplicates:
Example
print(thisset)
OUTPUT :
To determine how many items a set has, use the len() function.
Example
print(len(thisset))
OUTPUT :
Example
OUTPUT :
Example
OUTPUT :
type()
From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
Example
OUTPUT :
Example
OUTPUT :
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:
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.
2 print(item)
seattle
new york
chicago
sydney
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.
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’.
0 : london
1 : seattle
2 : new york
3 : chicago
4 : sydney
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.
3 print(item)
seattle
new york
chicago
Sydney
We can also convert a set explicitly to a list in order to iterate over it. We shall take the same list
as before:
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)
1 for i in range(0,len(my_list)):
2 print(my_list[i])
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
3 print(my_list[i])
4 i=i+1
Output:
london
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.
seattle
new york
chicago
sydney
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.
Using the zip() function, we shall create two iterables for each set – ‘i1’ and ‘i2’. Then, we shall
print i1 and i2.
2 print(i1, i2)
40 100
10 200
50 300
20 400
30 500
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:
# Output: {1, 2, 3, 4}
update(): Adds elements from another iterable (such as a list or another set) to a set.
# Output: {1, 2, 3, 4, 5}
remove(): Removes an element from a set. Raises a KeyError if the element is not found.
# 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.
# 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}
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}
# 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}
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.
Output:
Output:
frozenset Object is : frozenset({'Geeks', 'for'})
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"}
Output:
Python3
# creating a list
favourite_subject = ["OS", "DBMS", "Algo"]
# creating a frozenset
f_subject = frozenset(favourite_subject)
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"