Chapter 2
Chapter 2
Question 1
1. position
2. integer position
3. index
4. location
Answer
index
Question 2
1. exists
2. in
3. into
4. inside
Answer
in
Question 3
1. integer
2. mutable
3. immutable
4. any of these
Answer
immutable
Reason — Dictionaries are indexed by keys and its keys must be of any immutable type.
Question 4
>>>str = "hello"
>>>str[:2]
>>>
1. he
2. lo
3. olleh
4. hello
Answer
he
Reason — str[:2] here slicing operation begins from index 0 and ends at index 1. Hence the
output will be 'he'.
Question 5
1. list
2. dictionary
3. array
4. tuple
Answer
list
Reason — A list can store a sequence of values belonging to any data type and they are depicted
through square brackets.
Question 6
What data type is the object below ?
L = 1, 23, 'hello', 1
1. list
2. dictionary
3. array
4. tuple
Answer
tuple
Reason — For creating a tuple, enclosing the elements inside parentheses is optional. Even if
parentheses are omitted as shown here, still this statement will create a tuple.
Question 7
To store values in terms of key and value, what core data type does Python provide ?
1. list
2. tuple
3. class
4. dictionary
Answer
dictionary
Reason — Dictionaries are mutable with elements in the form of a key:value pair that associate
keys to values.
Question 8
1. (6.0, 27.0)
2. (6.0, 9.00)
3. (6, 27)
4. [6.0, 27.0]
5. [6, 27]
Answer
(6.0, 27.0)
Reason — The value of expression is in round brackets because it is tuple.
3 + 3.00 = 6.0
3**3.0 = 3 x 3 x 3 = 27.0
Question 9
1. del AL[2]
2. AL[2:3] = []
3. AL[2:2] = []
4. AL[2] = []
5. AL.remove(3)
Answer
del AL[2]
AL[2:3] = []
AL.remove(3)
Reason — del AL[2] — The del keyword deletes the element from the list AL from index 2.
AL[2:3] = [] — The slicing of the list AL[2:3] begins at index 2 and ends at index 2. Therefore,
the element at index 2 will be replaced by an empty list [].
AL.remove(3) — The remove() function removes an element from the list AL from index 3."
Question 10
1. This is a string
2. 'This is a string'
3. (This is a string)
4. "This is a string"
Answer
'This is a string'
"This is a string"
Question 11
You have the following code segment :
String1 = "my"
String2 = "work"
print(String1 + String2)
What is the output of this code?
1. my work
2. work
3. mywork
4. my
Answer
Output
mywork
Reason — The + operator creates a new string by joining the two operand strings.
Question 12
String1 = "my"
String2 = "work"
print(String1+String2.upper())
What is the output of this code?
1. mywork
2. MY Work
3. myWORK
4. My Work
Answer
Output
myWORK
Reason — string.upper() method returns a copy of the string converted to uppercase. The +
operator creates a new string by joining the two operand strings.
Question 13
Which line of code produces an error ?
1. "one" + 'two'
2. 1+2
3. "one" + "2"
4. '1' + 2
Answer
'1' + 2
Reason — The + operator has to have both operands of the same type either of number type (for
addition) or of string type (for concatenation). It cannot work with one operand as string and one
as a number.
Question 14
1. "7"
2. "34"
3. 34
4. 24
Answer
Output
34
Reason — The + operator concatenates two strings and int converts it to integer type.
int("3" + "4")
= int("34")
= 34
Question 15
Answer
Line 4
Reason — Index 5 is out of range because list has 5 elements which counts to index 4.
Question 16
Answer
Question 17
1. dictionary
2. string
3. tuple
4. list
Answer
list
Reason — A list can store a sequence of values belonging to any data type and enclosed in
square brackets.
Question 18
Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is incorrect ?
1. print(T[1])
2. T[2] = -29
3. print(max(T))
4. print(len(T))
Answer
T[2] = -29
Question 1
Question 2
Question 3
Question 4
Part of a string containing some contiguous characters from the string is called string slice.
Question 5
The * operator when used with a list/string and an integer, replicates the list/string.
Question 6
Question 8
Question 9
The del statement can remove an individual item or a slice from a list.
Question 10
Question 11
Question 12
Question 13
Question 14
The values() function returns all values from Key : value pair of a dictionary.
Question 15
The items() function returns all the Key : value pairs as (key, value) sequences.
True/False Questions
Question 1
False
Reason — Lists are ordered sequences. In the above two lists, even though the elements are
same, they are at different indexes (i.e., different order). Hence, they are two different lists.
Question 2
Answer
False
Reason — A list can store any data types and even list can contain another list as element.
Question 3
Answer
True
Question 4
Answer
False
Reason — A list is a standard data type of python that can store a sequence of values belonging
to any data type.
Question 5
Answer
True
Answer
True
Reason — Dictionaries are indexed by keys. Hence its keys must be of any non-mutable type.
Question 7
You can combine a numeric value and a string by using the + symbol.
Answer
False
Reason — The + operator has to have both operands of the same type either of number type (for
addition) or both of string type (for concatenation). It cannot work with one operand as string
and one as a number.
Question 8
The clear( ) removes all the elements of a dictionary but does not delete the empty dictionary.
Answer
True
Reason — The clear() method removes all items from the dictionary and the dictionary becomes
empty dictionary post this method. del statement removes the complete dictionary as an object.
Question 9
The max( ) and min( ) when used with tuples, can work if elements of the tuple are all of the
same type.
Answer
True
Reason — Tuples should contain same type of elements for max() and min() method to work.
Question 10
False
Reason — In Python, a list of characters and a string type are not similar. Strings are immutable
sequences of characters, while lists are mutable sequences that can contain various data types.
Lists have specific methods and behaviors that differ from strings, such as append(), extend(),
pop() etc.
Question 11
For any index n, s[:n] + s[n:] will give you original string s.
Answer
True
Reason — s[:n] — The slicing of a string starts from index 0 and ends at index n-1.
s[n:] — The slicing of a string starts from index n and continues until the end of the string.
So when we concatenate these two substrings we get original string s.
Question 12
Answer
False
Question 1
Assertion. Lists and Tuples are similar sequence types of Python, yet they are two different data
types.
Reason. List sequences are mutable and Tuple sequences are immutable.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
Lists and tuples are similar sequence types in python, but they are distinct data types. Both are
used to store collections of items, but they have different properties and use cases. Lists are
mutable, meaning you can add, remove, or modify elements after the list is created. Tuples, on
the other hand, are immutable, meaning once a tuple is created, its contents cannot be changed.
Question 2
Assertion. Modifying a string creates another string internally but modifying a list does not
create a new list.
Reason. Strings store characters while lists can store any type of data.
Answer
(b)
Both Assertion and Reason are true but Reason is not the correct explanation of Assertion.
Explanation
In Python, strings are immutable, meaning once they are created, their contents cannot be
changed. Whenever we modify a string, python creates a new string object to hold the modified
contents, leaving the original string unchanged. On the other hand, lists in python are mutable,
meaning we can modify their contents after they have been created. When we modify a list,
python does not create a new list object. Instead, it modifies the existing list object in place.
Strings are sequences of characters, and each character in a string can be accessed by its index.
Lists, on the other hand, can store any type of data, including integers, floats, strings.
Question 3
Assertion. Modifying a string creates another string internally but modifying a list does not
create a new list.
Reason. Strings are immutable types while lists are mutable types of python.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
In Python, strings are immutable, meaning once they are created, their contents cannot be
changed. Whenever we modify a string, python creates a new string object to hold the modified
contents, leaving the original string unchanged. On the other hand, lists in python are mutable,
meaning we can modify their contents after they have been created. When we modify a list,
python does not create a new list object. Instead, it modifies the existing list object in place.
Question 4
Assertion. Dictionaries are mutable, hence its keys can be easily changed.
Reason. Mutability means a value can be changed in place without having to create new storage
for the changed value.
Answer
(d)
Explanation
Dictionaries are indexed by keys and each key must be immutable and unique. However, the
dictionary itself is mutable, meaning that we can add, remove, or modify key-value pairs within
the dictionary without changing the identity of the dictionary object itself. Mutability refers to
the ability to change a value in place without creating a new storage location for the changed
value.
Question 5
Reason. The values of a dictionary can change but keys of dictionary cannot be changed because
through them data is hashed.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
A dictionary is a unordered set of key : value pairs and are indexed by keys. The values of a
dictionary can change but keys of dictionary cannot be changed because through them data is
hashed. Hence dictionaries are mutable but keys are immutable and unique.
Question 6
Reason. In Insertion sort, each successive element is picked and inserted at an appropriate
position in the sorted part of the array.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
Insertion sort is a sorting algorithm that builds a sorted list, one element at a time from the
unsorted list by inserting the element at its correct position in sorted list. In Insertion sort, each
successive element is picked and inserted at an appropriate position in the previously sorted
array.
Question 1
Answer
Strings in python are stored as individual characters in contiguous memory locations, with two-
way index for each location. The index (also called subscript) is the numbered position of a letter
in the string. Indices begin 0 onwards in the forward direction up to length-1 and -1,-2, .... up to -
length in the backward direction. This is called two-way indexing.
Question 2
Write a python script that traverses through an input string and prints its characters in different
lines - two characters per line.
Answer
Output
Enter name:python
py
th
on
Question 3
Answer
A list is a standard data type of python that can store a sequence of values belonging to any type.
Lists are mutable i.e., we can change elements of a list in place. Their dynamic nature allows for
flexible manipulation, including appending, inserting, removing, and slicing elements. Lists offer
significant utility in data storage, iteration, and manipulation tasks.
Question 4
What do you understand by mutability ? What does "in place" task mean ?
Answer
Mutability means that the value of an object can be updated by directly changing the contents of
the memory location where the object is stored. There is no need to create another copy of the
object in a new memory location with the updated values. Examples of mutable objects in python
include lists, dictionaries.
In python, "in place" tasks refer to operations that modify an object directly without creating a
new object or allocating additional memory. For example, list methods like append(), extend(),
and pop() perform operations in place, modifying the original list, while string methods like
replace() do not modify the original string in place but instead create a new string with the
desired changes.
Question 5
Start with the list [8, 9, 10]. Do the following using list functions:
Answer
1. listA[1] = 17
2. listA.extend([4, 5, 6])
3. listA.pop(0)
4. listA.sort()
5. listA = listA * 2
6. listA.insert(3, 25)
Question 6
What's a[1 : 1] if a is a string of at least two characters ? And what if string is shorter ?
Answer
a[x:y] returns a slice of the sequence from index x to y - 1. So, a[1 : 1] will return an empty list
irrespective of whether the list has two elements or less as a slice from index 1 to index 0 is an
invalid range.
Question 7
What are the two ways to add something to a list ? How are they different ?
Answer
The difference between the append() and extend() methods in python is that append() adds one
element at the end of a list, while extend() can add multiple elements, given in the form of a list,
to a list.
Example
append method:
Question 8
What are the two ways to remove something from a list? How are they different ?
Answer
The two ways to remove something from a list are:
The difference between the pop() and del is that pop() method is used to remove single item from
the list, not list slices whereas del statement is used to remove an individual item, or to remove
all items identified by a slice.
Example
pop() method:
lst = [1, 2, 3, 4, 5]
del lst[2:4]
print(lst)
Output — [1, 2, 5]
Question 9
Answer
List Tuple
Lists are mutable sequences of Python i.e., we can Tuples are immutable sequences of Python i.e., we
change elements of a list in place. cannot change elements of a tuple in place.
The syntax to create list is <list-name> = The syntax to create tuple is <tuple-name> = (value,
[value,.....] ....)
Lists cannot be used as keys in dictionary. Tuples can be used as keys in dictionary.
List Tuple
Lists cannot be used as elements of a set. Tuples can be used as elements of a set.
Lists are slower compared to tuples. Tuples are faster compared to lists.
Question 10
Answer
1. states = []
2. states.append('Delhi')
3. states.append('Punjab')
4. states2 = ['Rajasthan', 'Gujarat', 'Kerala']
5. states2.insert(0,'Odisha')
6. states2.insert(2,'Tripura')
7. a = states2.index('Gujarat')
states2.insert(a - 1,'Haryana')
8. b = states2.pop(4)
print(b)
Question 11
Answer
Tuples are used to store multiple items in a single variable. It is a collection which is ordered and
immutable i.e., the elements of the tuple can't be changed in place. Tuples are useful when values
to be stored are constant and need to be accessed quickly.
Question 12
If a is (1, 2, 3)
Answer
1. a * 3 ⇒ (1, 2, 3, 1, 2, 3, 1, 2, 3)
(a, a, a) ⇒ ((1, 2, 3), (1, 2, 3), (1, 2, 3))
So, a * 3 repeats the elements of the tuple whereas (a, a, a) creates nested tuple.
2. Yes, both a * 3 and a + a + a will result in (1, 2, 3, 1, 2, 3, 1, 2, 3).
3. This colon indicates (:) simple slicing operator. Tuple slicing is basically used to obtain a
range of items.
tuple[Start : Stop] ⇒ returns the portion of the tuple from index Start to index Stop
(excluding element at stop).
a[1:1] ⇒ This will return empty list as a slice from index 1 to index 0 is an invalid range.
4. Both are creating tuple slice with elements falling between indexes start and stop.
a[1:2] ⇒ (2,)
It will return elements from index 1 to index 2 (excluding element at 2).
a[1:1] ⇒ ()
a[1:1] specifies an invalid range as start and stop indexes are the same. Hence, it will
return an empty list.
Question 13
Answer
a = (30) ⇒ It will be treated as an integer expression, hence a stores an integer 30, not a tuple.
a = (30,) ⇒ It is considered as single element tuple since a comma is added after the element to
convert it into a tuple.
Question 14
Write a Python statement to declare a Dictionary named ClassRoll with Keys as 1, 2, 3 and
corresponding values as 'Reena', 'Rakesh', 'Zareen' respectively.
Answer
Question 15
Answer
Question 16
Answer
1. a Python string
2. a number
3. a tuple (containing only immutable entries)
Question 17
Though tuples are immutable type, yet they cannot always be used as keys in a dictionary. What
is the condition to use tuples as a key in a dictionary ?
Answer
For a tuple to be used as a key in a dictionary, all its elements must be immutable as well. If a
tuple contains mutable elements, such as lists, sets, or other dictionaries, it cannot be used as a
key in a dictionary.
Question 18
Dictionary is a mutable type, which means you can modify its contents ? What all is modifiable
in a dictionary ? Can you modify the keys of a dictionary ?
Answer
Yes, we can modify the contents of a dictionary.
Values of key-value pairs are modifiable in dictionary. New key-value pairs can also be added to
an existing dictionary and existing key-value pairs can be removed.
However, the keys of the dictionary cannot be changed. Instead we can add a new key : value
pair with the desired key and delete the previous one.
For example:
d = { 1 : 1 }
d[2] = 2
print(d)
d[1] = 3
print(d)
d[3] = 2
print(d)
del d[2]
print(d)
Output
{1: 1, 2: 2}
{1: 3, 2: 2}
{1: 3, 2: 2, 3: 2}
{1: 3, 3: 2}
Explanation
Question 19
How is del D and del D[<key>] different from one another if D is a dictionary ?
Answer
del D deletes the entire dictionary D. After executing del D, the variable D is no longer defined,
and any attempt to access D will result in a NameError.
del D[<key>] deletes the key-value pair associated with the specified key from the dictionary D.
After executing del D[<key>], the dictionary D still exists, but the specified key and its
corresponding value are removed from the dictionary.
For example:
Output
{1:'a'}
NameError: name 'd' is not defined.
Question 20
Create a dictionary named D with three entries, for keys 'a', 'b' and 'c'. What happens if you try to
index a nonexistent key (D['d']) ? What does python do if you try to assign to a nonexistent key
d.
(e.g., D['d'] = 'spam') ?
Answer
1. In this example, the dictionary D does not contain the key 'd'. Therefore, attempting to
access this key by D['d'] results in a KeyError because the key does not exist in the
dictionary.
2. If we try to assign a value to a nonexistent key in a dictionary, python will create that
key-value pair in the dictionary. In this example, the key 'd' did not previously exist in the
dictionary D. When we attempted to assign the value 'spam' to the key 'd', python created
a new key-value pair 'd': 'spam' in the dictionary D.
Output
Question 21
Answer
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Heap Sort
5. Quick Sort
Question 22
Answer
Bubble Sort :
In Bubble sort, the adjoining values are compared and exchanged if they are not in proper order.
This process is repeated until the entire array is sorted.
Insertion Sort :
Insertion sort is a sorting algorithm that builds a sorted list one element at a time from the
unsorted list by inserting the element at its correct position in sorted list.
Question 1(a)
y = str(123)
x = "hello" \* 3
print(x, y)
x = "hello" + "world"
y = len(x)
print(y, x)
Answer
Output
hellohellohello 123
10 helloworld
Explanation
str(123) converts the number 123 to string and stores in y so y becomes "123". "hello" * 3
repeats "hello" 3 times and stores it in x so x becomes "hellohellohello".
"hello" + "world" concatenates both the strings so x becomes "helloworld". As "helloworld"
contains 10 characters so len(x) returns 10.
Question 1(b)
x = "hello" + \
"to Python" + \
"world"
for char in x :
y = char
print(y, ':', end=" ")
Answer
Output
h : e : l : l : o : t : o : : P : y : t : h : o : n : w : o : r : l
: d :
Explanation
The code concatenates three strings "hello", "to Python", and "world" into the variable x. Then, it
iterates over each character in x using a for loop. For each character, it assigns it to the
variable y and prints y followed by a colon and space, all on the same line due to the end="
" parameter.
Question 1(c)
x = "hello world"
print(x[:2], x[:-2], x[-2:])
print(x[6], x[2:4])
print(x[2:-3], x[-4:-2])
Answer
Output
he hello wor ld
w ll
llo wo or
Explanation
print(x[:2], x[:-2], x[-2:]) —
x[:2] extracts the substring from the beginning of x up to index 1, resulting in "he".
x[:-2] extracts the substring from the beginning of x up to the third last character, resulting in
"hello wor".
x[-2:] extracts the substring from the last two characters of x until the end, resulting in "ld".
Hence, output of this line becomes he hello wor ld
print(x[6], x[2:4]) —
x[6] retrieves the character at index 6, which is 'w'.
x[2:4] extracts the substring from index 2 up to index 3, resulting in "ll".
Hence, output of this line becomes w ll
print(x[2:-3], x[-4:-2]) —
x[2:-3] extracts the substring from index 2 up to the fourth last character, resulting in "llo wo".
x[-4:-2] extracts the substring from the fourth last character to the third last character, resulting in
"or".
Hence, output of this line becomes llo wo or
Question 2
Write a short Python code segment that adds up the lengths of all the words in a list and then
prints the average (mean) length.
Answer
Output
Explanation
1. The code prompts the user to enter a list of words and assigns it to the
variable word_list.
2. We iterate over word_list using for loop. Inside the loop, length of each word gets
added to total_length variable.
3. Average length is calculated by dividing total_length by the number of words
in word_list.
Question 3
Predict the output of the following code snippet ?
a = [1, 2, 3, 4, 5]
print(a[3:0:-1])
Answer
Output
[4, 3, 2]
Explanation
The slicing notation a[start:stop:step] extracts a portion of the list from index start to stop-
1 with a specified step. In the slicing part a[3:0:-1]:
Putting it together:
a[3:0:-1]
This extracts elements from index 3 to (0+1) in reverse order with a step of -1.
[4, 3, 2]
Question 4(a)
arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = "")
Answer
Output
234566
Explanation
1. arr is initialised as a list with elements [1, 2, 3, 4, 5, 6].
2. for loop iterates over the indices from 1 to 5. For each index i, it assigns the value
of arr[i] to arr[i - 1], effectively shifting each element one position to the left. After
this loop, the list arr becomes [2, 3, 4, 5, 6, 6].
3. Second for loop iterates over the indices from 0 to 5 and prints each element of the
list arr without newline characters because of end="" parameter. Then it prints the
elements of the modified list arr, resulting in 234566.
Question 4(b)
Answer
Output
1 #
1 # 2 #
1 # 2 # 3 #
Explanation
Question 5(a)
Question 5(b)
Answer
There are no errors in this python code. Lists in python can contain elements of any type. As lists
are mutable so t[0] = 6 is also valid.
Question 5(c)
Answer
t[4] = 6 will raise an error as we are trying to change the value at index 4 but it is outside the
current range of the list t. As t has 3 elements so its indexes are 0, 1, 2 only.
Question 5(d)
t = 'hello'
t[0] = "H"
Answer
t[0] = "H" will raise an error because strings in python are immutable, meaning we cannot
change individual characters in a string after it has been created. Therefore, attempting to assign
a new value to t[0] will result in an error.
Question 5(e)
1. In the list [Amar, Shveta, Parag], each element should be enclosed in quotes because
they are strings.
2. The equality comparison operator is '==' instead of = for checking equality.
3. if statement should be lowercase.
Question 6
Assuming words is a valid list of words, the program below tries to print the list in reverse. Does
it have an error ? If so, why ? (Hint. There are two problems with the code.)
Answer
1. The start index len(words) is invalid for the list words as it will have indexes from 0
to len(words) - 1.
2. The end index being 0 means that the last element of the list is missed as the list will be
iterated till index 1 only.
Question 7
What would be the output of following code if ntpl = ("Hello", "Nita", "How's", "life ?") ?
(a, b, c, d) = ntpl
print("a is:", a)
print("b is:", b)
print("c is:", c)
print("d is:", d)
ntpl = (a, b, c, d)
print(ntpl[0][0] + ntpl[1][1], ntpl[1])
Answer
Output
a is: Hello
b is: Nita
c is: How's
d is: life ?
Hi Nita
Explanation
ntpl is a tuple containing 4 elements. The statement (a, b, c, d) = ntpl unpacks the tuple ntpl
into the variables a, b, c, d. After that, the values of the variables are printed.
The statement ntpl = (a, b, c, d) forms a tuple with values of variables a, b, c, d and assigns
it to ntpl. As these variables were not modified, so effectively ntpl still contains the same values
as in the first statement.
ntpl[0] ⇒ "Hello"
∴ ntpl[0][0] ⇒ "H"
ntpl[1] ⇒ "Nita"
∴ ntpl[1][1] ⇒"i"
Question 8
Answer
Output
True
Explanation
Tuples can be declared with or without parentheses (parentheses are optional). Here, tuple_a is
declared without parentheses where as tuple_b is declared with parentheses but both are
identical. As both the tuples contain same values so the equality operator ( == ) returns true.
Question 9
1. True
2. False
3. 1
4. Exception
Answer
Output
True
Explanation
In the given python code snippet, id1 and id2 will point to two different objects in memory
as del rec deleted the original dictionary whose id is stored in id1 and created a new dictionary
with the same contents storing its id in id2. However, id1 == id2 will compare the contents of
the two dictionaries pointed to by id1 and id2. As contents of both the dictionaries are same
hence it returns True. If in this code we add another line print(id1 is id2) then this line will
print False as id1 and id2 point to two different dictionary objects in memory.
Question 10
Answer
Output
Explanation
A dictionary my_dict with two key-value pairs, 'name': 'Aman' and 'age': 26 is initialized. Then
updates the value associated with the key 'age' to 27. Then adds a new key-value pair 'address':
'Delhi' to the dictionary my_dict. The items() method returns all of the items in the dictionary as
a sequence of (key, value) tuples. In this case, it will print [('name', 'Aman'), ('age', 27),
('address', 'Delhi')].
Question 11
Write a method in python to display the elements of list thrice if it is a number and display the
element terminated with '#' if it is not number.
Answer
def display(my_list):
for item in my_list:
if item.isdigit():
print(item * 3)
else:
print(item + '#')
display(my_list = eval(input("Enter the list :")))
Output
Explanation
1. The code prompts the user to enter the elements of the list separated by spaces and stores
the input as a single string in the variable my_list.
2. Then splits the input string my_list into individual elements and stores them in a new list
called new_list.
3. Then for loop iterates over each element in the new_list.
4. The isdigit() method is used to check if all characters in the string are digits. If it's true
(i.e., if the element consists only of digits), then it prints the element concatenated with
itself three times. Otherwise, if the element contains non-digit characters, it prints the
element concatenated with the character '#'.
Question 12
Answer
(i) isupper() method is used to check if a string contains only uppercase letters.
Question 13
my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
my_dict[(1,2)] = 12
sum = 0
for k in my_dict:
sum += my_dict[k]
print(sum)
print(my_dict)
Answer
Output
30
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}
Explanation
Question 1
Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after
the area code and the next three numbers. For example, 017-555-1212 is a legal input.
Display if the phone number entered is valid format or not and display if the phone number is
valid or not (i.e., contains just the digits and dash at specific places).
Solution
Output
=====================================
Question 2
Write a program that should prompt the user to type some sentence(s) followed by "enter". It
should then print the original sentence(s) and the following statistics relating to the sentence(s):
Number of words
Number of characters (including white-space and punctuation)
Percentage of characters that are alpha numeric
Hints
Solution
for ch in str :
if ch.isspace() :
spaceCount += 1
elif ch.isalnum() :
alnumCount += 1
print("Original Sentences:")
print(str)
Output
Enter a few sentences: Python was conceived in the late 1980s by Guido
van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands.
Its implementation began in December 1989. Python 3.0 was released on
3 December 2008.
Original Sentences:
Python was conceived in the late 1980s by Guido van Rossum at Centrum
Wiskunde & Informatica (CWI) in the Netherlands. Its implementation
began in December 1989. Python 3.0 was released on 3 December 2008.
Number of words = 34
Number of characters = 205
Alphanumeric Percentage = 80.48780487804879
Question 3
Write a program that takes any two lists L and M of the same size and adds their elements
together to form a new list N whose elements are sums of the corresponding elements in L and
M. For instance, if L = [3, 1, 4] and M = [1, 5, 9], then N should equal [4, 6, 13].
Solution
for i in range(len(L)):
N.append(L[i] + M[i])
print("List N:")
print(N)
Output
Question 4
Write a program that rotates the elements of a list so that the element at the first index moves to
the second index, the element in the second index moves to the third index, etc., and the element
in the last index moves to the first index.
Solution
l = l[-1:] + l[:-1]
print("Rotated List")
print(l)
Output
Question 5
Write a short python code segment that prints the longest word in a list of words.
Solution
Output
Question 6
Write a program that creates a list of all the integers less than 100 that are multiples of 3 or 5.
Solution
a = []
for i in range(0,100):
if (i % 3 == 0) or (i % 5 == 0) :
a.append(i)
print(a)
Output
[0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36,
39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72,
75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99]
Question 7
Define two variables first and second so that first = "Jimmy" and second = "Johny". Write a short
python code segment that swaps the values assigned to these two variables and prints the results.
Solution
first = "Jimmy"
second = "Johny"
temp = first
first = second
second = temp
print("first =", first)
print("second =", second)
Output
first = Johny
second = Jimmy
Question 8
Write a python program that creates a tuple storing first 9 terms of Fibonacci series.
Solution
lst = [0,1]
a = 0
b = 1
c = 0
for i in range(7):
c = a + b
a = b
b = c
lst.append(c)
tup = tuple(lst)
Question 9
Create a dictionary whose keys are month names and whose values are the number of days in the
corresponding months.
(a) Ask the user to enter a month name and use the dictionary to tell them how many days are in
the month.
(d) Print out the (key-value) pairs sorted by the number of days in each month.
Solution
days_in_months = {
"january":31,
"february":28,
"march":31,
"april":30,
"may":31,
"june":30,
"july":31,
"august":31,
"september":30,
"october":31,
"november":30,
"december":31
}
if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)
day_month_lst = []
for i in days_in_months:
day_month_lst.append([days_in_months[i], i])
day_month_lst.sort()
month_day_lst =[]
for i in day_month_lst:
month_day_lst.append([i[1], i[0]])
sorted_days_in_months = dict(month_day_lst)
print()
print("Months sorted by days:", sorted_days_in_months)
Output
Question 10
Write a function called addDict(dict1, dict2) which computes the union of two dictionaries. It
should return a new dictionary, with all the items in both its arguments (assumed to be
dictionaries). If the same key appears in both arguments, feel free to pick a value from either.
Solution
Output
Question 11
Write a program to sort a dictionary's keys using Bubble sort and produce the sorted keys as a
list.
Solution
Output
Question 12
Write a program to sort a dictionary's values using Bubble sort and produce the sorted values as a
list.
Solution
Output
Enter the dictionary: {'w':34, 'a':5, 'g':45, 't':21}
Sorted values: [5, 21, 34, 45]