chapter 2 solutions
chapter 2 solutions
Question 1
The numbered position of a letter in a string is called...............
1. position
2. integer position
3. index
4. location
Answer
index
Reason — The index is the numbered position of a letter in the string.
Question 2
The operator ............... tells if an element is present in a sequence or not.
1. exists
2. in
3. into
4. inside
Answer
in
Reason — in is membership operator which returns True if a character or a
substring exists in the given string else returns False.
Question 3
The keys of a dictionary must be of ............... types.
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
Following set of commands is executed in shell, what will be the output?
>>>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
What data type is the object below ?
L = [1, 23, 'hello', 1]
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
What is the value of the following expression ?
3 + 3.00, 3**3.0
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
List AL is defined as follows : AL = [1, 2, 3, 4, 5]
Which of the following statements removes the middle element 3 from it so
that the list AL equals [1, 2, 4, 5] ?
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
Which two lines of code are valid strings in Python ?
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"
Reason — Strings are enclosed within single or double quotes.
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
You have the following code segment :
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
What is the output of this code ?
>>> int("3" + "4")
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
Which line of code will cause an error ?
1. num= [5, 4, 3, [2], 1]
2. print(num[0])
3. print(num[3][0])
4. print(num[5])
1. Line 3
2. Line 2
3. Line 4
4. Line 1
Answer
Line 4
Reason — Index 5 is out of range because list has 5 elements which counts to
index 4.
Question 16
Which is the correct form of declaration of dictionary ?
Question 17
Identify the valid declaration of L:
L = ['Mon', '23', 'hello', '60.5']
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
Reason — Tuples are immutable. Hence we cannot perform item-assignment
in tuples.
Fill in the Blanks
Question 1
Strings in Python store their individual letters in Memory
in contiguous location.
Question 2
Operator + when used with two strings, gives a concatenated string.
Question 3
Operator + when used with a string and an integer gives an error.
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
Tuples or Strings are not mutable while lists are.
Question 7
Using list() function, you can make a true copy of a list.
Question 8
The pop() function is used to remove an item from a list/dictionary.
Question 9
The del statement can remove an individual item or a slice from a list.
Question 10
The clear() function removes all the elements of a list/dictionary.
Question 11
Creating a tuple from a set of values is called packing.
Question 12
Creating individual values from a tuple's elements is called unpacking.
Question 13
The keys() method returns all the keys in a dictionary.
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
Do both the following represent the same list.
['a', 'b', 'c']
['c', 'a', 'b']
Answer
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
A list may contain any type of objects except another list.
Answer
False
Reason — A list can store any data types and even list can contain another
list as element.
Question 3
There is no conceptual limit to the size of a list.
Answer
True
Reason — The list can be of any size.
Question 4
All elements in a list must be of the same type.
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
A given object may appear in a list more than once.
Answer
True
Reason — List can have duplicate values.
Question 6
The keys of a dictionary must be of immutable types.
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
A list of characters is similar to a string type.
Answer
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
A dictionary can contain keys of any valid Python types.
Answer
False
Reason — The keys of a dictionary must be of immutable types.
Assertions and Reasons
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)
Assertion is false but Reason is true.
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
Assertion. Dictionaries are mutable but their keys are immutable.
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
Assertion. In Insertion Sort, a part of the array is always sorted.
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.
Type A: Short Answer Questions/Conceptual Questions
Question 1
What is the internal structure of python strings ?
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
name = input("Enter name:")
for i in range(0, len(name), 2):
print(name[i:i+2])
Output
Enter name:python
py
th
on
Question 3
Discuss the utility and significance of Lists, briefly.
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:
1. Set the second entry (index 1) to 17
2. Add 4, 5 and 6 to the end of the list
3. Remove the first entry from the list
4. Sort the list
5. Double the list
6. Insert 25 at index 3
Answer
listA = [8, 9, 10]
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 two methods to add something to a list are:
1. append method — The syntax of append method is list.append(item).
2. extend method — The syntax of extend method is list.extend(<list>).
Difference
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:
lst1 = [10, 12, 14]
lst1.append(16)
print(lst1)
Output — [10, 12, 14, 16]
extend method:
t1 = ['a', 'b', 'c']
t2 = ['d', 'e']
t1.extend(t2)
print(t1)
Output — ['a', 'b', 'c', 'd', 'e']
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:
1. pop method — The syntax of pop method is List.pop(<index>).
Question 9
What is the difference between a list and a tuple ?
Answer
List Tuple
Lists are mutable sequences of Python Tuples are immutable sequences of Python
List Tuple
i.e., we can change elements of a list in i.e., we cannot change elements of a tuple in
place. 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.
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
In the Python shell, do the following :
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
Discuss the utility and significance of Tuples, briefly.
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)
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
What is the difference between (30) and (30,) ?
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
ClassRoll = {1:'Reena', 2:'Rakesh', 3:'Zareen'}
Question 15
Why is a dictionary termed as an unordered collection of objects ?
Answer
A dictionary is termed as an unordered collection of objects because the
elements in a dictionary are not stored in any particular order. Unlike string,
list and tuple, a dictionary is not a sequence. For a dictionary, the printed
order of elements is not the same as the order in which the elements are
stored.
Question 16
What type of objects can be used as keys in dictionaries ?
Answer
Keys of a dictionary must be of immutable types such as
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
d is a dictionary which contains one key-value pair.
d[2] = 2 adds new key-value pair to d.
d[1] = 3 modifies value of key 1 from 1 to 3.
d[3] = 2 adds new key-value pair to d.
del d[2] deletes the key 2 and its corresponding value.
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:
d = {1: 'a' , 2 : 'b'}
del d[2]
print(d)
del d
print(d)
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.
D = {'a' : 1, 'b' : 2, 'c' : 3}
D['d'] = 'spam'
Output
D = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 'spam'}
Question 21
What is sorting ? Name some popular sorting techniques.
Answer
Sorting refers to arranging elements of a sequence in a specific order —
ascending or descending.
Sorting Techniques are as follows :
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Heap Sort
5. Quick Sort
Question 22
Discuss Bubble sort and Insertion sort techniques.
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.
Type B: Application Based Questions
Question 1(a)
What will be the output produced by following code fragments ?
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)
What will be the output produced by following code fragments ?
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)
What will be the output produced by following code fragments ?
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
word_list = eval(input("Enter a list of words: "))
total_length = 0
for word in word_list:
total_length += len(word)
average_length = total_length / len(word_list)
print("Average length of words:", average_length)
Output
Enter a list of words: ["apple", "banana", "orange", "kiwi"]
Average length of words: 5.25
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]:
Question 4(a)
Predict the output of the following code snippet?
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)
Predict the output of the following code snippet ?
Numbers = [9, 18, 27, 36]
for Num in Numbers :
for N in range(1, Num % 8) :
print(N, "#", end=" ")
print( )
Answer
Output
1#
1#2#
1#2#3#
Explanation
Question 5(a)
Find the errors. State reasons.
t = (1, "a", 9.2)
t[0] = 6
Answer
t[0] = 6 will raise a TypeError as tuples are immutable (i.e., their elements
cannot be changed after creation).
Question 5(b)
Find the errors. State reasons.
t = [1, "a", 9.2]
t[0] = 6
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)
Find the errors. State reasons.
t = [1, "a", 9.2]
t[4] = 6
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)
Find the errors. State reasons.
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)
Find the errors. State reasons.
for Name in [Amar, Shveta, Parag]
IF Name[0] = 'S':
print(Name)
Answer
The errors in this code are:
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.)
for i in range(len(words), 0, -1):
print(words[i], end=' ')
Answer
There are two issue in range(len(words), 0, -1):
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.
Question 8
What will be the output of the following code ?
tuple_a = 'a', 'b'
tuple_b = ('a', 'b')
print (tuple_a == tuple_b)
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
What will be the output of the following code snippet ?
rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ", "Country" : "USA"}
id1 = id(rec)
del rec
rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ", "Country" : "USA"}
id2 = id(rec)
print(id1 == id2)
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
Write the output of the code given below :
my_dict = {"name" : "Aman", "age" : 26}
my_dict['age'] = 27
my_dict['address'] = "Delhi"
print(my_dict.items())
Answer
Output
dict_items([('name', 'Aman'), ('age', 27), ('address', 'Delhi')])
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.
For example, if the content of list is as follows :
List = ['41', 'DROND', 'GIRIRAJ', '13', 'ZARA']
The output should be
414141
DROND#
GIRIRAJ#
131313
ZAR#
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
Enter the elements of the list separated by spaces:41 DROND GIRIRAJ 13
ZARA
414141
DROND#
GIRIRAJ#
131313
ZARA#
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
Name the function/method required to
(i) check if a string contains only uppercase letters.
(ii) gives the total length of the list.
Answer
(i) isupper() method is used to check if a string contains only uppercase
letters.
(ii) len() gives the total length of the list.
Question 13
What will be the output of the following code snippet ?
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
Solution
phNo = input("Enter the phone number: ")
length = len(phNo)
if length == 12 \
and phNo[3] == "-" \
and phNo[7] == "-" \
and phNo[:3].isdigit() \
and phNo[4:7].isdigit() \
and phNo[8:].isdigit() :
print("Valid Phone Number")
else :
print("Invalid Phone Number")
Output
Enter the phone number: 017-555-1212
Valid Phone Number
=====================================
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
Assume any consecutive sequence of non-blank characters in a word.
Solution
str = input("Enter a few sentences: ")
length = len(str)
spaceCount = 0
alnumCount = 0
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
print("Enter two lists of same size")
L = eval(input("Enter first list(L): "))
M = eval(input("Enter second list(M): "))
N = []
for i in range(len(L)):
N.append(L[i] + M[i])
print("List N:")
print(N)
Output
Enter two lists of same size
Enter first list(L): [3, 1, 4]
Enter second list(M): [1, 5, 9]
List N:
[4, 6, 13]
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 = eval(input("Enter the list: "))
print("Original List")
print(l)
l = l[-1:] + l[:-1]
print("Rotated List")
print(l)
Output
Enter the list: [8, 10, 13, 25, 7, 11]
Original List
[8, 10, 13, 25, 7, 11]
Rotated List
[11, 8, 10, 13, 25, 7]
Question 5
Write a short python code segment that prints the longest word in a list of
words.
Solution
my_list = eval(input("Enter the list : "))
longest_word = ""
max_length = 0
Output
Enter the list : ['red', 'yellow', 'green', 'blue']
Longest word: yellow
Enter the list : ['lion', 'elephant', 'tiger', 'monkey', 'hippopotamus']
Longest word: hippopotamus
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)
print("9 terms of Fibonacci series are:", tup)
Output
9 terms of Fibonacci series are: (0, 1, 1, 2, 3, 5, 8, 13, 21)
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.
(b) Print out all of the keys in alphabetical order.
(c) Print out all of the months with 31 days.
(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
Enter name of month: may
There are 31 days in may
Months in alphabetical order are: ['april', 'august', 'december', 'february',
'january', 'july', 'june', 'march', 'may', 'november', 'october', 'september']
Months with 31 days: january march may july august october december
Months sorted by days: {'february': 28, 'april': 30, 'june': 30, 'november': 30,
'september': 30, 'august': 31, 'december': 31, 'january': 31, 'july': 31, 'march':
31, 'may': 31, 'october': 31}
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
def addDict(dict1, dict2):
union_dict = {}
for key, value in dict1.items():
union_dict[key] = value
for key, value in dict2.items():
union_dict[key] = value
return union_dict
Output
Union of dict1 and dict2: {'a': 1, 'b': 3, 'c': 4}
Question 11
Write a program to sort a dictionary's keys using Bubble sort and produce
the sorted keys as a list.
Solution
my_dict = eval(input("Enter the dictionary: "))
keys = list(my_dict.keys())
l = len(keys)
for i in range(l):
for j in range(0, l - i - 1):
if keys[j] > keys[j + 1]:
keys[j], keys[j + 1] = keys[j + 1], keys[j]
print("Sorted keys:",keys)
Output
Enter the dictionary: {'c':10, 'f':87, 'r':23, 'a':5}
Sorted keys: ['a', 'c', 'f', 'r']
Question 12
Write a program to sort a dictionary's values using Bubble sort and produce
the sorted values as a list.
Solution
my_dict = eval(input("Enter the dictionary: "))
values = list(my_dict.values())
l = len(values)
for i in range(l):
for j in range(0, l - i - 1):
if values[j] > values[j + 1]:
# Swap values
values[j], values[j + 1] = values[j + 1], values[j]
print("Sorted values:", values)
Output
Enter the dictionary: {'w':34, 'a':5, 'g':45, 't':21}
Sorted values: [5, 21, 34, 45]