0% found this document useful (0 votes)
17 views

Assignment 2 Solutions

The document discusses dictionary, list, and string methods in Python. It provides examples of using dictionary keys and values, list indexing and slicing, and string formatting methods. Methods like append(), insert(), remove(), sort(), upper(), lower(), strip(), and walk() are explained.

Uploaded by

Adarsha M R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Assignment 2 Solutions

The document discusses dictionary, list, and string methods in Python. It provides examples of using dictionary keys and values, list indexing and slicing, and string formatting methods. Methods like append(), insert(), remove(), sort(), upper(), lower(), strip(), and walk() are explained.

Uploaded by

Adarsha M R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Assignment-2 Solution

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.

Traversing using for loop:

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

i) Adding values to a list:


ü To add new values to a list, the append() and insert() methods can be used.
ü The append() method adds the argument to the end of the list.

The insert() method insert a value at any index in the list.


ü The first argument to insert() is the index for the new value, and the second argument is the
new value to be inserted.
ii) Removing values from a list:
• To remove values from a list, the remove( ) and del( ) methods can be used.
• The del statement is used when we know the index of the value we want to remove
from the list.
• The remove() method is used when we know the value we want to remove from the
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

iii) Finding a value in a list:


• To find a value in a list we can use index value.
• The first value in the list is at index 0, the second value is at index 1, and the third
value is at index 2, and so on. The negative indexes can also be used.
• Example:

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

3. What is the difference between copy.copy( ) and copy.deepcopy( ) functions applicable


to a List or Dictionary in Python? Give suitable examples for each.

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]]

4. Discuss the following Dictionary methods in Python with examples.


(i) get() (ii) items() (iii) keys() (iv) values()
(i) get( ): Dictionaries have a get() method that takes two arguments:
Ø The key of the value to retrieve
Ø A fallback value to return if that key does not exist.

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

6. Explain references with example.


ü Reference: A reference is a value that points to some bit of data, and a list reference is a
value that points to a list.

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.

(ii) To right-justify, left-justify, and center 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!

• The files must be closed after once it is read or written.

12. Explain saving of variables using shelve module.


• The variables can be saved in Python programs to binary shelf files using the shelve
module.
• This helps the program to restore data to variables from the hard drive.
• The shelve module will let us add Save and Open features to your program.
• Example:

13. How do we specify and handle absolute, relative paths?


There are two ways to specify a file path.
1. An absolute path, which always begins with the root folder
2. A relative path, which is relative to the program’s current working directory
• The os.path module provides functions for returning the absolute path of a relative
path and for checking whether a given path is an absolute path.
1. Calling os.path.abspath(path) will return a string of the absolute path of the argument. This
is an easy way to convert a relative path into an absolute one.
2. Calling os.path.isabs(path) will return True if the argument is an absolute path and False if
it is a relative path.
3. Calling os.path.relpath(path, start) will return a string of a relative path from the start path
to path. If start is not provided, the current working directory is used as the start path.
Since C:\Python34 was the working directory when os.path.abspath() was called, the “single-
dot” folder represents the absolute path 'C:\\Python34'.

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.

You might also like