Python Programming Unit III
Python Programming Unit III
Python Programming Unit III
UNIT III
PROF.AJAY PASHANKAR
ASSISTANT PROFESSOR DEPARTMENT OF CS & IT
K.M.AGRAWAL COLLEGE KALYAN
www.profajaypashankar.com
Lists :
A list is an ordered set of values, where each value is identified by an
index.
The values that make up a list are called its elements .
Lists are similar to strings, which are ordered sets of characters, except
that the elements of a list can have any type.
Lists and strings—and other things that behave like ordered sets—are
called sequences .
The list is the most versatile datatype available in Python, which can be
written as a list of comma-separated values (items) between square
brackets.
Important thing about a list is that the items in a list need not be of the
same type.
There are several ways to create a new list; the simplest is to enclose the elements
in square brackets ([ and ]):
[10, 20, 30, 40] ["spam", "bungee", "swallow"]
A list within another list is said to be nested .
Finally, there is a special list that contains no elements.
It is called the empty list, and is denoted []. Like numeric 0 values and the empty
string, the empty list is false in a boolean expression:
-------------------------------------------------------------------------------------------------
Values and Accessing Elements:
The values stored in a list can be accessed using the slice operator ([ ] and
[:]) with indexes starting at 0 in the beginning of the list and working their
way to end -1.
The plus (+) sign is the list concatenation operator, and the asterisk (*) is
the repetition operator.
#!/usr/bin/python3
list = [ 'abcd', 786 , 2.23, 'john',
70.2 ] tinylist = [123, 'john']
print (list)
print (list[0]) print (list[1:3])
# Prints complete list
# Prints first element of the list
# Prints elements starting from 2nd
till 3rd print (list[2:])
# Prints elements starting
from 3rd element print (tinylist * 2) # Prints list two
times
print (list + tinylist) # Prints concatenated lists
Lists are mutable :
Unlike strings lists are mutable , which means we can change their elements.
Using the bracket operator on the left side of an assignment, we can update one of
the elements:
>>> fruit = ["banana", "apple", "quince"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print fruit
[’pear’, ’apple’, ’orange’]
Explanation:
The bracket operator applied to a list can appear anywhere in an expression. When it
appears on the left side of an assignment, it changes one of the elements in the list,
so the first element of fruit has been changed from "banana" to "pear", and the last
from "quince" to "orange".
An assignment to an element of a list is called item assignment.
Item assignment does not work for strings:
>>> my_string = "TEST"
>>> my_string[2] = "X"
Traceback (most recent call last): File "<stdin>", line 1, in
<module>
TypeError: ’str’ object does not support item assignment
---------------------------------------------------------------------------------------------------------------------------------
but it does for lists:
>>> my_list = ["T", "E", "S", "T"]
>>> my_list[2] = "X"
>>> my_list
[’T’, ’E’, ’X’, ’T’]
With the slice operator we can update several elements at once:
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3] = ["x", "y"]
>>> print a_list
[’a’, ’x’, ’y’, ’d’, ’e’, ’f’]
We can also remove elements from a list by assigning the empty list to them:
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3] = []
>>>
print a_list [’a’,
’d’,
’e’,
’f’]
And we can add elements to a list by squeezing them into an empty slice at the
desired location:
>>> a_list = ["a", "d", "f"]
>>> a_list[1:1] = ["b", "c"]
>>> print a_list
[’a’, ’b’, ’c’, ’d’, ’f’]
>>> a_list[4:4] = ["e"]
>>> print a_list
[’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
---------------------------------------------------------------------------------------------------
Deleting elements from List :
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting.
You can use the remove() method if you do not know exactly which items to delete.
#!/usr/bin/python3
list = ['physics', 'chemistry', 1997, 2000] print (list)
del list[2]
print ("After deleting value at index 2 : ", list)
list1 = ['physics', 'chemistry', 'maths'] list2=list(range(5)) #creates list of numbers between 0-4
list1.extend('Extended List :', list2)
print (list1)
List index() Method
The index() method returns the lowest index in list that obj appears.
Syntax
Following is the syntax for index() method-
list.index(obj)
Parameters
obj - This is the object to be find out.
Return Value
This method returns index of the found object otherwise raises an exception indicating that
the value is not found.
Return Value
This method does not return any value but it inserts the given element at the given index.
list1 = ['physics', 'chemistry', 'maths'] list1.insert(1, 'Biology')
print ('Final list : ', list1)
Final list : ['physics', 'Biology', 'chemistry', 'maths']
List pop() Method :
Description
The pop() method removes and returns last object or obj from the list.
Syntax
Following is the syntax for pop() method-
list.pop(obj=list[-1])
Parameters
obj - This is an optional parameter, index of the object to be removed from the list.
Return Value
This method returns the removed object from the list.
list1 = ['physics', 'Biology', 'chemistry', 'maths'] list1.pop()
print ("list now : ", list1) list1.pop(1)
print ("list now : ", list1)
o/p
['physics', 'Biology', 'chemistry']
['physics', 'chemistry']
Listremove()Method :
Parameters
obj - This is the object to be removed from the list.
Return Value
This method does not return any value but removes the given object from the list.
Example :
list1 = ['physics', 'Biology', 'chemistry', 'maths'] list1.remove('Biology')
print ("list now : ", list1) list1.remove('maths')
print ("list now : ", list1)
list now :
['physics', 'chemistry', 'maths']
['physics', 'chemistry']
Listreverse()Method
Description
The reverse() method reverses objects of list in place.
Syntax
Following is the syntax for reverse() method-
list.reverse()
Parameters
NA
Return Value
This method does not return any value but reverse the given object from the list. \
Syntax
Following is the syntax for len() method-
len(dict)
Example
The following example shows the usage of len() method.
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} print ("Length : %d" % len (dict))
When we run the above program, it produces the following result-
Length : 3
Dictionarystr()Method
Description
The method str() produces a printable string representation of a dictionary.
Syntax
Following is the syntax for str() method −
str(dict)
Parameters
dict - This is the dictionary.
Return Value
This method returns string representation.
Example
The following example shows the usage of str() method.
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} print ("Equivalent String : %s" % str (dict))
Equivalent String : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
Dictionary type() Method
Description
The method type() returns the type of the passed variable. If passed variable is dictionary then
it would return a dictionary type.
Syntax
Following is the syntax for type() method-
type(dict)
Parameters
dict - This is the dictionary.
Return Value
This method returns the type of the passed variable.
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} print ("Variable Type : %s" % type (dict))
o/p
Variable Type : <type 'dict'>
Python includes the following dictionary methods-
Dictionaryclear()Method
Description
The method clear() removes all items from the dictionary.
Syntax
Following is the syntax for clear() method-
dict.clear()
Parameters
NA
Return Value
This method does not return any value.
Example :
dict = {'Name': 'Zara', 'Age': 7} print ("Start Len : %d" % len(dict)) dict.clear()
print ("End Len : %d" % len(dict))
o/p
Start Len : 2
End Len : 0
Dictionary copy() Method
Description
The method copy() returns a shallow copy of the dictionary.
Syntax
Following is the syntax for copy() method-
dict.copy()
Parameters
NA
Return Value
This method returns a shallow copy of the dictionary.
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} dict2 = dict1.copy()
print ("New Dictionary : ",dict2)
o/p:
New dictionary : {'Name': 'Manni', 'Age': 7, 'Class':'First'}
NOTE:
Python provides two types of copy i.e. 1)shallow 2)deep
Shallow Copy
A shallow copy creates a new object which stores the reference of the original elements.
So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference
of nested objects. This means, a copy process does not recurse or create copies of nested
objects itself.
---------------------------------------------------------------------------------------------------
Deep Copy
A deep copy creates a new object and recursively adds the copies of nested objects present in
the original elements.
The deep copy creates independent copy of original object and all its nested objects.
Dictionary fromkeys() Method :
Description
The method fromkeys() creates a new dictionary with keys from seq and values set to value.
Syntax
Following is the syntax for fromkeys() method-
dict.fromkeys(seq[, value]))
Parameters
• seq - This is the list of values which would be used for dictionary keys preparation.
• value - This is optional, if provided then value would be set to thisvalue
Return Value
This method returns the list.
Example:
seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq)
print ("New Dictionary : %s" % str(dict)) dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s" % str(dict)
Dictionary get() Method
Description
The method get() returns a value for the given key. If the key is not available then returns
default value None.
Syntax
Following is the syntax for get() method-
dict.get(key, default=None)
Parameters
• key - This is the Key to be searched in the dictionary.
• default - This is the Value to be returned in case key does not exist.
Return Value
This method returns a value for the given key. If the key is not available, then returns default
value as None.
dict = {'Name': 'Zara', 'Age': 27}
print ("Value : %s" % dict.get('Age'))
print ("Value : %s" % dict.get('Sex', "NA"))
Dictionary items() Method
Description
The method items() returns a list of dict's (key, value) tuple pairs.
Syntax :
Following is the syntax for items() method-
dict.items()
Parameters
NA
Return Value
This method returns a list of tuple pairs.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.items())
o/p
Value : [('Age', 7), ('Name', 'Zara')]
Dictionary keys() Method :
Description
The method keys() returns a list of all the available keys in the dictionary.
Syntax
Following is the syntax for keys() method-
dict.keys()
Parameters
NA
Return Value
This method returns a list of all the available keys in the dictionary.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.keys())
o/p
Value : ['Age', 'Name']
Dictionary setdefault() Method :
The method setdefault() is similar to get(), but will set dict[key]=default if the key is not
already in dict.
Syntax
Following is the syntax for setdefault() method-
dict.setdefault(key, default=None)
Parameters
• key - This is the key to be searched.
• default - This is the Value to be returned in case key is not found.
Return Value
This method returns the key value available in the dictionary and if given key is not available
then it will return provided default value.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.setdefault('Age', None)) print ("Value : %s" % dict.setdefault('Sex',
None)) print (dict)
Dictionary update() Method
Description
The method update() adds dictionary dict2's key-values pairs in to dict. This function does not
return anything.
Syntax
Following is the syntax for update() method-
dict.update(dict2)
Parameters
dict2 - This is the dictionary to be added into dict.
Return Value
This method does not return any value.
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' } dict.update(dict2)
print ("updated dict : ", dict)
o/p
updated dict : {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
Dictionaryvalues()Method
Description
The method values() returns a list of all the values available in a given dictionary.
Syntax
Following is the syntax for values() method-
dict.values()
Parameters
NA
Return Value
This method returns a list of all the values available in a given dictionary.
Example
The following example shows the usage of values() method.
#!/usr/bin/python3
dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'} print ("Values : ", list(dict.values()))
When we run above program, it produces following result-
Values : ['female', 7, 'Zara']
Files
Python provides basic functions and methods necessary to manipulate files by default. You can
do most of the file manipulation using a file object.
The open Function
Before you can read or write a file, you have to open it using Python's built-in open() function.
This function creates a file object, which would be utilized to call other support methods
associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details-
file_name: The file_name argument is a string value that contains the name of the file that
you want to access.
access_mode: The access_mode determines the mode in which the file has to be opened,
i.e., read, write, append, etc.
A complete list of possible values is given below in the table. This is an optional parameter and
the default file access mode is read (r).
buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is
1, line buffering is performed while accessing a file. If you specify the buffering value as an
integer greater than 1, then buffering action is performed with the indicated buffer size. If
The File Object Attributes :
Once a file is opened and you have one file object, you can get various information related to
that file.
Here is a list of all the attributes related to a file object-
The tell() method tells you the current position within the file; in other words, the
next read or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset
argument indicates the number of bytes to be moved. The from argument specifies
the reference position from where the bytes are to be moved.
If from is set to 0, the beginning of the file is used as the reference position. If it is
set to 1, the current position is used as the reference position. If it is set to 2 then the
end of the file would b
# Open a file
fo = open("foo.txt", "r+") str = fo.read(10)
print ("Read String is : ", str)
# Check current positione taken as the reference position.
position = fo.tell()
print ("Current file position : ", position)
# Reposition pointer at the beginning once again position = fo.seek(0, 0)
str = fo.read(10)
print ("Again read String is : ", str)
# Close opened file fo.close()
The rename()Method
The rename() method takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is an example to rename an existing file test1.txt-
#!/usr/bin/python3 import os
# Rename a file from test1.txt to test2.txt os.rename( "test1.txt", "test2.txt" )
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.
Syntax
os.remove(file_name)
Example
Following is an example to delete an existing file test2.txt-
#!/usr/bin/python3 import os
# Delete file test2.txt os.remove("text2.txt")
Directories :
All files are contained within various directories, and Python has no problem handling these
too.
The os module has several methods that help you create, remove, and change directories.
#!/usr/bin/python3 import os
# Create a directory "test" os.mkdir("test")
The chdir() Method
You can use the chdir() method to change the current directory.
The chdir() method takes an argument, which is the name of the directory that you want to
make the current directory.
Syntax
os.chdir("newdir")
Example
Following is an example to go into "/home/newdir" directory-
#!/usr/bin/python3 import os
# Changing a directory to "/home/newdir" os.chdir("/home/newdir")
The getcwd() Method
The getcwd() method displays the current working directory.
Syntax :
os.getcwd()
#!/usr/bin/python3 import os
# This would give location of the current directory os.getcwd()
---------------------------------------------------------------------------------------------------------
The rmdir() Method
The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should beremoved.
Syntax :
os.rmdir('dirname')
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
Exceptions :
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object that
represents an error.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
Python provides two types of exceptions i.e. 1)built-in 2)user defined
Built-in Exceptions
:
Handling Exceptions :
If you have some suspicious code that may raise an exception, you can defend your program
by placing the suspicious code in a try: block. After the try: block, include an except:
statement, followed by a block of code which handles the problem as elegantly as possible.
Syntax
Here is simple syntax of
try....except...else blocks-
Here are few important points about the above-mentioned syntax-
• A single try statement can have multiple except statements. This is useful when the try block
contains statements that may throw different types of exceptions.
• You can also provide a generic except clause, which handles any exception.
• After the except clause(s), you can include an else-clause. The code in the else- block
executes if the code in the try: block does not raise an exception.
• The else-block is a good place for code that does not need the try: block's protection.
Example:
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully") fh.close()
Exception with Arguments :
An exception can have an argument, which is a value that gives additional
information about the problem. The contents of the argument vary by exception.
You capture an exception's argument by supplying a variable in the except clause as
follows-
If you write the code to handle a single exception, you can have a variable follow the name of the
exception in the except statement. If you are trapping multiple exceptions, you can have a
variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The
variable can receive a single value or multiple values in the form of a tuple. This tuple usually
contains the error string, the error number, and an errorlocation.
Example
Following is an example for a single exception-
#!/usr/bin/python3
# Define a function here. def temp_convert(var): try:
returnint(var)
except ValueError as Argument:
print("The argument does not contain numbers\n",Argument)
# Call above function here. temp_convert("xyz")
o/p
The argument does not contain numbers invalid literal for int() with base 10: 'xyz'
User-defined Exceptions :
Python also allows you to create your own exceptions byderiving classes fromthe standard
built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from
RuntimeError. This is useful when you need to display more specific information when an
exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The
variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def init (self, arg):
self.args = arg
So once you have defined the above class, you can raise the exception as follows-
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
QUICK REVISION OF UNIT III :
A list is an ordered set of values, where each value is identified by an index.
Important thing about a list is that the items in a list need not be of the same type.
Lists are mutable .
An assignment to an element of a list is called item assignment
Tuple are very similar to lists with only difference that element values of a tuple can
not be changed and tuple elements are put between parentheses instead of square
bracket.
append method used to add element in list at last position .
tuple is a sequence of immutable Python objects.
Dictionary :Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces.
More than one entry per key is not allowed.
Keys must be immutable.
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions.
Python provides two types of exceptions i.e. 1)built-in 2)user defined
VISIT
https://www.profajaypashankar.com
For more study material and notes .
VISIT
https://www.youtube.com/channel/UCu4Bd22zM6RpvHWC9YHBh5Q?view_as=subscriber
For more lectures .