Unit-III Python Notes
Unit-III Python Notes
in
Unit – III
Chapter-I ( Lists)
1.1 INTRODUCTION TO LIST
The data type list is an ordered sequence which is mutable and made up of one or more
elements
Unlike a string which consists of only characters, a list can have elements of different
data types, such as integer, float, string, tuple or even another list.
A list is very useful to group together elements of mixed data types.
Elements of a list are enclosed in square brackets and are separated by comma. Like
string indices, list indices also start from 0.
Example :
Syntax :-
list_name[index] = new_value
If we try to concatenate a list with elements of some other data type, TypeError occurs.
1.2.2 Repetition :
Python allows us to replicate a list using repetition operator depicted by symbol *
1.2.3 Membership :
Like strings, the membership operators in checks if the element is present in the list and
returns True, else returns False
The not in operator returns True if the element is not present in the list, else it returns
False.
1.2.4 Slicing :
List slicing refers to accessing a specific portion or a subset of the list for some operation
while the original list remains unaffected.
The slicing operator in python can take 3 parameters.
Syntax of list slicing:
list_name[start:stop:steps]
The start represents the index from where the list slicing is supposed to begin. Its
default value is 0, i.e. it begins from index 0.
The stop represents the last index up to which the list slicing will go on. Its default
value is (length(list)-1) or the index of last element in the list.
The step Integer value which determines the increment between each index for
slicing.
list1 =['Red','Green','Blue','Black']
for item in list1:
print(item)
Output :
Red
Green
Blue
Black
1.3.2 List Traversing using while Loop
list1 =['Red','Green','Blue','Black'] Output :
i = 0 Red
while i < len(list1): Green
print(list1[i])
Blue
i += 1
Black
>>> list1.reverse()
>>> list1
[99, 28, 89, 12, 66, 34]
>>> list1.reverse()
>>> list1
['Dog','Elephant',
'Cat','Lion','Zebra','Tiger']
>>>list1=['Tiger','Zebra','Lio
n', 'Cat', 'Elephant' ,'Dog']
>>> list1.sort()
>>> list1
Sorts the elements of the ['Cat','Dog','Elephant',
sort() 'Lion', 'Tiger', 'Zebra']
given list in-place
>>>list1 = [34,66,12,89,28,99]
>>> list1
[99,89,66,34,28,12]
>>>list1 = [23,45,11,67,85,56]
The statement list2 = list1 does not create a new list. Rather, it just makes
list1 and list2 refer to the same list object.
Here list2 actually becomes an alias of list1. Therefore, any changes made to
either of them will be reflected in the other list.
1.7 Aliasing
Giving a new name to an existing list is called 'aliasing'. The new name is called 'alias name'.
x = [10,20,30,40,50]
y = x # x is aliased as y
print(x)
print(y)
def increment(list2):
for i in range(0, len(list2)):
list2[i] += 5
list1 = [10,20,30,40,50]
print("The list before the function call")
print(list1)
increment(list1)
print("The list after the function call")
print(list1)
1.9 Tuples
Syntax
tuple_name = (element_1, element_2,...)
Example :-
#tuple1 is the tuple of integers
tuple1 = (1, 2, 3, 4, 5)
#tuple2 is the tuple of mixed data types
tuple2 =('Stats',65,'Maths',75)
#tuple3 is the tuple with list as an element
tuple3 = (10,20,30,[40,50])
#tuple4 is the tuple with tuple as an element
tuple4 = (1,2,3,4,5,(10,20))
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
tuple1 = (1, 3, 5, 7, 9)
tuple2 = (2,4,6,8,10)
print(tuple1+tuple2)
tuple3 = (1,2,3,4,5)
tuple3 = tuple3 + (6,) #single element is appended to tuple3
print(tuple3)
print(tuple3[1:4]) #elements from index 1 to index 3
print(tuple3[:5]) #slice starts from zero index
tuple4 = ('Hello','World')
print(tuple4 * 3)
print('Hello' in tuple4)
print('Hello' not in tuple4)
(num1,num2) = (10,20)
print(num1)
print(num2)
record = ( "Pooja",40,"CS")
(name,rollNo,subject) = record
print(name,rollNo,subject)
If there is an expression on the right side then first that expression is evaluated and
finally the result is assigned to the tuple.
Output :
15
25
1.12 Tuple as return value
Functions can return tuples as return values.
def circleInfo(r):
#Return (circumference, area) of a circle of radius r
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(circleInfo(10))
1.13 Dictionaries :
Syntax
dict1=dict()
print(dict1)
dict2 = {'Santhosh':95,'Avanthi':89,'College':92}
print(dict2)
The items of a dictionary are accessed via the keys rather than via their relative
positions or indices. Each key serves as the index and maps to a value
dict2 = {'Santhosh':95,'Avanthi':89,'College':92}
print(dict2['Avanthi'])
print(dict2['Santhosh'])
dict2 = {'Santhosh':95,'Avanthi':89,'College':92}
dict2['Meena'] = 78
print(dict2)
dict2['Avanthi'] = 93.5
print(dict2)
>>>dict1 = {'Mohan':95,
'Ram':89, 'Suhel':92,
'Sangeeta':85}
Returns a list of
keys() keys in the
>>> dict1.keys()
dictionary
dict_keys(['Mohan', 'Ram',
'Suhel','Sangeeta'])
>>> dict2 =
appends the key- {'Sohan':79,'Geeta':89}
value pair of the
>>> dict1.update(dict2)
dictionary passed
update() as the argument to
>>> dict1
the key-value pair
of the given {'Mohan': 95, 'Ram': 89,
dictionary 'Suhel': 92, 'Sangeeta': 85,
'Sohan': 79, 'Geeta':89}
>>> dict2
>>> dict1
>>> dict1
>>> dict1 =
{'Mohan':95,'Ram':89,
'Suhel':92, 'Sangeeta':85}
Deletes or clear all
clear() the items of
>>> dict1.clear()
the dictionary
>>> dict1
{ }
dict1 = {'Santhosh':95,'Avanthi':89,'College':92}
print(dict1)
print("Displays the keys :",dict1.keys())
print("Displays the values :",dict1.values())
print("Displays the items : ",dict1.items())
print("length of the dictionary :",len(dict1))
print("value corresponding to the key college
:",dict1.get('College'))
del dict1['Avanthi']
print("Values after Deleting : ",dict1)
Syntax
list=[ expression for item in list if conditional ]
Example Program:
def Selectionsort(num):
n=len(num)
for i in range(n):
for j in range(i+1,n):
if(num[i]>num[j]):
temp=num[i]
num[i]=num[j]
num[j]=temp
print("sorted List is ", num)
Selectionsort([5,2,4,1,9])
def insertionsort(num):
for i in range(len(num)):
for j in range(0,i):
if(num[i]<num[j]):
temp=num[i]
num[i]=num[j]
num[j]=temp
print("sorted List is ", num)
insertionsort([5,2,4,1,9])
1.20 Histogram
def histogram(items):
for n in items:
output=''
num=n
while (num>0):
output += '*'
num=num-1
print(output)
histogram([2,3,5,6,4])
Output :
**
***
*****
******
****
Syntax
file = open("file_name.extension", "mode")
There are four different modes you can open a file to:
• read():The read() method of file object reads whole data from the open file. But,
optionally we can also specify the number of characters to be read.
• readlines():The readline( ) method of file object reads all lines until file end
and returns an object list.
fptr=open("D:Sample.txt","w")
fptr.writelines("Hello world \n Welcome to Technology")
fptr.close()
Output :
Output :
The no.of words in file is 6
The shutil module provides some easy to use methods using which we can remove as well
as copy a file in Python.
The copyfile() method copies the content from the source to the target file using the file
paths. It returns the target file path.
The target file path must be writeable or else an OSerror exception would occur.
import shutil
shutil.copyfile( 'sample.txt' , 'targ.txt' )
fptr=open("targ.txt","r")
print(fptr.read())
fptr.close()
output :
Python is an interpreted programming language
Example :
Marks = 42
print('Ramu got %d Marks.' % Marks)
Output :
Ramu got 42 Marks.
2.4 Errors and Exception
Errors are the problems in a program due to which the program will stop the
execution.
Syntax errors are detected when we have not followed the rules of the particular
programming language while writing a program. These errors are also known as
parsing errors.
The Python programming language provides three keywords to handle the exceptions.
try
except
finally
2.5.1 try
The try keyword is used to define a block of code which may cause an exception.
Syntax:
try:
statement(s)
2.5.2 except
The except keyword is used to define a block of code which handles the exception.
Syntax:
except:
statement(s)
2.5.3 finally
The finally keyword is used to define a block of code which is to execute, regardless of
an exception occurrence.
Syntax:
finally:
statement(s)
Note : The Python allows us to use an optional else keyword that can be used with try block.
The else is used to define a block of code to be executed if no exception were raised.
The following is the general syntax of exception handling in the Python.
Syntax:
try:
# the code that may raise an exception
except:
# the code that handles an exception
else:
# the code that to be executed if no exception were raised
finally:
# the code that must be executed
try:
x = int(input("enter first number: "))
y = int(input("enter second number: "))
result=x/y
print("The answer of x divide by y:", result)
except:
print("Can't divide with zero")
finally:
print("finally block")
When we run the above example code, it produces the following output.
When we run the above example code, it produces the following output for the values
a = r and b = 5. Here, the exception is a ValueError which can not be handled by the
above code.
2.7 Modules
In Python, a module is a python file containing functions, class, and variables. A module is
included in any python application using an import statement.
Save the above code as Calci.py so that the module can be used as Calci.
import Calci
print(Calci.add(10, 5))
print(Calci.sub(10, 5))
print(Calci.mul(10, 5))
print(Calci.div(10, 5))
2.8 Packages
A python package is a collection of modules. Modules that are related to each other are
mainly put in the same package. When a module from an external package is required
in a program, that package can be imported.
In Python, a package is a directory which must contains a __init__.py file. This file
can be an empty file.
A package in the Python can contain any file with .py extension including modules
def getStudents():
print("There are total 2500 students")
def getTeachers():
print("There are total 70 teachers")
Unit-III Questions
1. Explain about list in detail (List operations and Methods)
2. Write a short note on
(a) Aliasing
(b) cloning list
(c) list parameters
3. Explain tuple in detail
4. Explain Dictionaries in detail
5. Write a short note on advanced processing (list
comprehension)
6. Explain files in detail with an example programs
7. Exception handling (try, except and finally)
8. Write about Modules and Packages