Assignment 2 Solutions
Assignment 2 Solutions
Module-2
1. What is Dictionary in Python? How is it different from List data type? Explain how a
for loop can be used to traverse the keys of the Dictionary with an example.
Dictionary: A dictionary is a collection of many values. Indexes for dictionaries can use
many different data types, not just integers. Indexes for dictionaries are called keys, and a key
with its associated value is called a key-value pair. A dictionary is typed with braces, {}.
The dictionary is different from list data type:
• In lists the items are ordered and in dictionaries the items are unordered.
• The first item in a list exists. But there is no “first” item in a dictionary.
• The order of items matters for determining whether two lists are the same, it does
not matter in what order the key-value pairs are typed in a dictionary.
• Trying to access a key that does not exist in a dictionary will result in a KeyError
error message, in list “out-of-range” IndexError error message.
2. Explain the methods of List data type in Python for the following operations with
suitable code snippets for each.
(i) Adding values to a list ii) Removing values from a list
(iii) Finding a value in a list iv) Sorting the values in a list
• Attempting to delete a value that does not exist in the list will result in a ValueError
error.
• If the value appears multiple times in the list, only the first instance of the value will
be removed
• The expression 'Hello ' + spam[0] evaluates to 'Hello ' + 'cat' because spam[0]
evaluates to the string 'cat'. This expression in turn evaluates to the string value 'Hello
cat'.
• Negative index à spam[-1] à Retrieves last value.
iv) Sorting the values in a list
• Lists of number values or lists of strings can be sorted with the sort() method.
Copy module must be imported and can be used to make a duplicate copy of a mutable value
like a list or dictionary, not just a copy of a reference.
copy.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 create copies of nested
objects itself.
Example:
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.copy(old_list)
old_list[1][1] = 'AA'
print("Old list:", old_list)
print("New list:", new_list)
Output:
Old list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]
copy.deepcopy( ): A deep copy creates a new object and recursively adds the copies of
nested objects present in the original elements.
Example:
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
old_list[1][0] = 'BB'
print("Old list:", old_list)
print("New list:", new_list)
Output:
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
(ii) items( ): This method returns the dictionary values and keys in the form of tuples.
Ex: spam = {‘color’ : ‘red’ , ‘age’ : 27}
for i in spam.items( ):
print(i)
Output: (‘color’, ‘red’)
(‘age’, 27)
(iii) keys( ): This method returns the dictionary keys.
Ex: spam = {‘color’ : ‘red’ , ‘age’ : 27}
for i in spam.keys( ):
print(i)
Output: color
age
iv) values( ): This method returns the dictionary values.
Ex: spam = {‘color’ : ‘red’ , ‘age’ : 27}
for i in spam.values( ):
print(i)
Output: red
27
5. What is list? Explain the concept of list slicing with example.
List: A list is a value that contains multiple values in an ordered sequence.
Slicing: Extracting a substring from a string is called substring.
Ex.
Here, the list is created, and assigned reference to it in the spam variable.
ü In the next line copies only the list reference in spam to cheese, not the list value itself. This
means the values stored in spam and cheese now both refer to the same list.
ü When a function is called, the values of the arguments are copied to the parameter
variables.
• when eggs() is called, a return value is not used to assign a new value to spam.
• Even though spam and someParameter contain separate references, they both refer to
the same list.
• This is why the append('Hello') method call inside the function affects the list even
after the function call has returned.
7. What is dictionary? How it is different from list? Write a program to count the
number of occurrences of character in a string.
The dictionary is different from list data type:
• In lists the items are ordered and in dictionaries the items are unordered.
• The first item in a list exists. But there is no “first” item in a dictionary.
• The order of items matters for determining whether two lists are the same, it does
not matter in what order the key-value pairs are typed in a dictionary.
• Trying to access a key that does not exist in a dictionary will result in a KeyError
error message, in list “out-of-range” IndexError error message.
import pprint
x = input("Enter a String")
count = {}
for character in x:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
Module-3 solution
8. Explain the various string methods for the following operations with examples.
(i) Removing whitespace characters from the beginning, end or both sides of a string.
i) Removing whitespace characters from the beginning, end or both sides of a string.
• The strip() string method will return a new string without any whitespace
characters at the beginning or end.
• The lstrip() and rstrip() methods will remove whitespace characters from the
left and right ends, respectively.
ii) To right-justify, left-justify, and center a string.
• The rjust() and ljust() string methods return a padded version of the string they are
called on, with spaces inserted to justify the text.
• The first argument to both methods is an integer length for the justified string.
An optional second argument to rjust() and ljust() will specify a fill character other than a
space character.
The center() string method works like ljust() and rjust() but centers the text rather than
justifying it to the left or right.
9. List any six methods associated with string and explain each of them with example.
i) upper( ): This method is used to convert lower case characters into upper case characters.
Ex: x = ‘Python’
x = x.upper( )
PYTHON
ii) lower( ): This method is used to convert upper case characters into lower case characters.
Ex: x = ‘Python’
x = x.lower( )
python
iii) isupper( ): This method is used to check whether a string has at least one letter or
complete string is upper or not. It returns Boolean value.
Ex: x = ‘Python’
x = x.isupper( )
TRUE
Ex: y = ‘python’
y = y.isupper( )
FALSE
iv) islower( ): This method is used to check whether a string has at least one letter or
complete string is lower or not. It returns Boolean value.
Ex: x = ‘Python’
x = x.islower( )
TRUE
Ex: y = ‘PYTHON’
y = y.isupper( )
FALSE
v) isspace( ): Returns True if the string consists only of spaces, tabs, and newlines and is not
blank.
Ex: ‘ ‘.isspace( )
TRUE
vi) isalnum( ): Returns True if the string consists only of letters and numbers and is not
blank.
Ex: ‘hello123’.isalnum( )
TRUE
Ex: ‘ ‘.isalnum( )
FALSE
10. Describe the difference between Python os and os.path modules. Also, discuss the
following methods of os module
a) chdir() b) rmdir() c) walk() d) listdir() e) getcwd()
os module àIt is from the standard library and it provides a portable way of accessing and
using operating system dependent functionality.
os.path module à It is used to manipulate the file and directory paths and path names.
a) chdir( ) à This method is used to change from current working directory to the required
directory.
Ex: import os
os.chdir(“C:\\Windows\\System”)
b) rmdir( ) à This method is used to delete the folder at path. This folder must not contain any
files or folders.
c) walk( ) à This method is used to access or do any operation on each file in a folder.
Ex:
import os
for foldername, subfolder, filenames in os.walk(“C:\\Windows\\System”)
print(“The current folder is “+foldername)
d) listdir( ) à This method returns a list containing the names of the entries in the directory
given by path.
e) getcwd( ) à This method is used to get the current working directory.
Ex: import os
os.getcwd( )
11. Explain the file Reading/Writing process with suitable Python Program.
Reading File: read( ) and readlines( ) methods are used to read the contents of a file. read( )
method reads the contents of a file as a single string value whereas readlines( ) method reads
each line as a string value.
Ex.
Writing File: The file must be opened in order to write the contents to a file. It can be done
in two ways: wither in write mode or append mode. In write mode the contents of the existing
file will be overwritten whereas in append mode the contents will be added at the end of
existing file.
Ex: In the below example bacon.txt file is opened in write mode hence, all the contents will
be deleted and Hello world! Will be written.
Ex: In the below example bacon.txt file is opened in append mode hence, the contents will be
added after Hello world!
Calling os.path.dirname(path) will return a string of everything that comes before the last
slash in the path argument.
ü Calling os.path.basename(path) will return a string of everything that comes after the last
slash in the path argument.
Ex.