The numbered position of a letter in a string is called ...............
- position
- integer position
- index
- location
Answer
index
Reason — The index is the numbered position of a letter in the string.
The operator ............... tells if an element is present in a sequence or not.
- exists
- in
- into
- 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.
The keys of a dictionary must be of ............... types.
- integer
- mutable
- immutable
- any of these
Answer
immutable
Reason — Dictionaries are indexed by keys and its keys must be of any immutable type.
Following set of commands is executed in shell, what will be the output?
>>>str = "hello"
>>>str[:2]
>>>
- he
- lo
- olleh
- hello
Answer
he
Reason — str[:2]
here slicing operation begins from index 0 and ends at index 1. Hence the output will be 'he'.
What data type is the object below ?
L = [1, 23, 'hello', 1]
- list
- dictionary
- array
- tuple
Answer
list
Reason — A list can store a sequence of values belonging to any data type and they are depicted through square brackets.
What data type is the object below ?
L = 1, 23, 'hello', 1
- list
- dictionary
- array
- 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.
To store values in terms of key and value, what core data type does Python provide ?
- list
- tuple
- class
- dictionary
Answer
dictionary
Reason — Dictionaries are mutable with elements in the form of a key:value pair that associate keys to values.
What is the value of the following expression ?
3 + 3.00, 3**3.0
- (6.0, 27.0)
- (6.0, 9.00)
- (6, 27)
- [6.0, 27.0]
- [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
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] ?
- del AL[2]
- AL[2:3] = []
- AL[2:2] = []
- AL[2] = []
- 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."
Which two lines of code are valid strings in Python ?
- This is a string
- 'This is a string'
- (This is a string)
- "This is a string"
Answer
'This is a string'
"This is a string"
Reason — Strings are enclosed within single or double quotes.
You have the following code segment :
String1 = "my"
String2 = "work"
print(String1 + String2)
What is the output of this code?
- my work
- work
- mywork
- my
Answer
mywork
Reason — The + operator creates a new string by joining the two operand strings.
You have the following code segment :
String1 = "my"
String2 = "work"
print(String1+String2.upper())
What is the output of this code?
- mywork
- MY Work
- myWORK
- My Work
Answer
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.
Which line of code produces an error ?
- "one" + 'two'
- 1 + 2
- "one" + "2"
- '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.
What is the output of this code ?
>>> int("3" + "4")
- "7"
- "34"
- 34
- 24
Answer
34
Reason — The +
operator concatenates two strings and int
converts it to integer type.
int("3" + "4")
= int("34")
= 34
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])
- Line 3
- Line 2
- Line 4
- Line 1
Answer
Line 4
Reason — Index 5 is out of range because list has 5 elements which counts to index 4.
Which is the correct form of declaration of dictionary ?
- Day = {1:'Monday', 2:'Tuesday', 3:'wednesday'}
- Day = {1;'Monday', 2;'Tuesday', 3;'wednesday'}
- Day = [1:'Monday', 2:'Tuesday', 3:'wednesday']
- Day = {1'monday', 2'tuesday', 3'wednesday'}
Answer
Day = {1:'Monday', 2:'Tuesday', 3:'wednesday'}
Reason — The syntax of dictionary declaration is:
<dictionary-name> = {<key>:<value>, <key>:<value>}
According this syntax, Day = {1:'Monday', 2:'Tuesday', 3:'wednesday'} is the correct answer.
Identify the valid declaration of L:
L = ['Mon', '23', 'hello', '60.5']
- dictionary
- string
- tuple
- list
Answer
list
Reason — A list can store a sequence of values belonging to any data type and enclosed in square brackets.
Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is incorrect ?
- print(T[1])
- T[2] = -29
- print(max(T))
- print(len(T))
Answer
T[2] = -29
Reason — Tuples are immutable. Hence we cannot perform item-assignment in tuples.
Strings in Python store their individual letters in Memory in contiguous location.
Operator + when used with two strings, gives a concatenated string.
Operator + when used with a string and an integer gives an error.
Part of a string containing some contiguous characters from the string is called string slice.
The * operator when used with a list/string and an integer, replicates the list/string.
Tuples or Strings are not mutable while lists are.
Using list() function, you can make a true copy of a list.
The pop() function is used to remove an item from a list/dictionary.
The del statement can remove an individual item or a slice from a list.
The clear() function removes all the elements of a list/dictionary.
Creating a tuple from a set of values is called packing.
Creating individual values from a tuple's elements is called unpacking.
The keys() method returns all the keys in a dictionary.
The values() function returns all values from Key : value pair of a dictionary.
The items() function returns all the Key : value pairs as (key, value) sequences.
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.
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.
There is no conceptual limit to the size of a list.
Answer
True
Reason — The list can be of any size.
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.
A given object may appear in a list more than once.
Answer
True
Reason — List can have duplicate values.
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.
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.
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.
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.
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.
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.
A dictionary can contain keys of any valid Python types.
Answer
False
Reason — The keys of a dictionary must be of immutable types.
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.
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.
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.
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.
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.
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.
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.
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])
Enter name:python
py
th
on
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.
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.
Start with the list [8, 9, 10]. Do the following using list functions:
- Set the second entry (index 1) to 17
- Add 4, 5 and 6 to the end of the list
- Remove the first entry from the list
- Sort the list
- Double the list
- Insert 25 at index 3
Answer
listA = [8, 9, 10]
- listA[1] = 17
- listA.extend([4, 5, 6])
- listA.pop(0)
- listA.sort()
- listA = listA * 2
- listA.insert(3, 25)
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.
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:
append method — The syntax of append method is
list.append(item)
.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']
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:
pop method — The syntax of pop method is
List.pop(<index>)
.del statement — The syntax of del statement is
del list[<index>] # to remove element at index
del list[<start>:<stop>] # to remove elements in list slice
Difference
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:
t1 = ['k', 'a', 'e', 'i', 'p', 'q', 'u']
ele1 = t1.pop(0)
print(ele1)
Output — 'k'
del statement:
lst = [1, 2, 3, 4, 5]
del lst[2:4]
print(lst)
Output — [1, 2, 5]
What is the difference between a list and a tuple ?
Answer
List | Tuple |
---|---|
Lists are mutable sequences of Python i.e., we can change elements of a list in place. | Tuples are immutable sequences of Python i.e., we cannot change elements of a tuple in place. |
The syntax to create list is <list-name> = [value,.....] | The syntax to create tuple is <tuple-name> = (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. |
In the Python shell, do the following :
- Define a variable named states that is an empty list.
- Add 'Delhi' to the list.
- Now add 'Punjab' to the end of the list.
- Define a variable states2 that is initialized with 'Rajasthan', 'Gujarat', and 'Kerala'.
- Add 'Odisha' to the beginning of the list states2.
- Add 'Tripura' so that it is the third state in the list states2.
- Add 'Haryana' to the list states2 so that it appears before 'Gujarat'. Do this as if you DO NOT KNOW where 'Gujarat' is in the list. Hint. See what states2.index("Rajasthan") does. What can you conclude about what listname.index(item) does ?
- Remove the 5th state from the list states2 and print that state's name.
Answer
- states = []
- states.append('Delhi')
- states.append('Punjab')
- states2 = ['Rajasthan', 'Gujarat', 'Kerala']
- states2.insert(0,'Odisha')
- states2.insert(2,'Tripura')
- a = states2.index('Gujarat')
states2.insert(a - 1,'Haryana') - b = states2.pop(4)
print(b)
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.
If a is (1, 2, 3)
- what is the difference (if any) between a * 3 and (a, a, a) ?
- Is a * 3 equivalent to a + a + a ?
- what is the meaning of a[1:1] ?
- what is the difference between a[1:2] and a[1:1] ?
Answer
- 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. - Yes, both a * 3 and a + a + a will result in (1, 2, 3, 1, 2, 3, 1, 2, 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. - 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.
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.
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'}
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.
What type of objects can be used as keys in dictionaries ?
Answer
Keys of a dictionary must be of immutable types such as
- a Python string
- a number
- a tuple (containing only immutable entries)
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.
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)
{1: 1, 2: 2}
{1: 3, 2: 2}
{1: 3, 2: 2, 3: 2}
{1: 3, 3: 2}
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.
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)
{1:'a'}
NameError: name 'd' is not defined.
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
- 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.
- 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'
D = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 'spam'}
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 :
- Bubble Sort
- Insertion Sort
- Selection Sort
- Heap Sort
- Quick Sort
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.
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
hellohellohello 123
10 helloworld
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.
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
h : e : l : l : o : t : o : : P : y : t : h : o : n : w : o : r : l : d :
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.
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
he hello wor ld
w ll
llo wo or
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
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)
Enter a list of words: ["apple", "banana", "orange", "kiwi"]
Average length of words: 5.25
- The code prompts the user to enter a list of words and assigns it to the variable
word_list
. - We iterate over
word_list
usingfor
loop. Inside the loop, length of each word gets added tototal_length
variable. - Average length is calculated by dividing
total_length
by the number of words inword_list
.
Predict the output of the following code snippet ?
a = [1, 2, 3, 4, 5]
print(a[3:0:-1])
Answer
[4, 3, 2]
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]
:
start
is 3, which corresponds to the element with value 4.stop
is 0, but as element at stop index is excluded so slicing goes up to index 1.step
is -1, indicating that we want to step backward through the list.
Putting it together:
a[3:0:-1]
This extracts elements from index 3 to (0+1) in reverse order with a step of -1.
The output of the code will be:
[4, 3, 2]
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
234566
arr
is initialised as a list with elements [1, 2, 3, 4, 5, 6].for
loop iterates over the indices from 1 to 5. For each indexi
, it assigns the value ofarr[i]
toarr[i - 1]
, effectively shifting each element one position to the left. After this loop, the listarr
becomes[2, 3, 4, 5, 6, 6]
.- Second for loop iterates over the indices from 0 to 5 and prints each element of the list
arr
without newline characters because ofend=""
parameter. Then it prints the elements of the modified listarr
, resulting in234566
.
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
1 #
1 # 2 #
1 # 2 # 3 #
Numbers
is a list containing the numbers 9, 18, 27, and 36.- The outer for loop iterates over each element in the list
Numbers
. - The inner loop iterates over the range from 1 to the remainder of Num divided by 8. For example, if Num is 9, the range will be from 1 to 1 (9 % 8 = 1). If Num is 18, the range will be from 1 to 2 (18 % 8 = 2), and so on. Then it prints the value of N, followed by a "#", and ensures that the output is printed on the same line by setting end=" ".
- After both loops, it prints an empty line, effectively adding a newline character to the output.
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).
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.
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.
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.
Find the errors. State reasons.
for Name in [Amar, Shveta, Parag]
IF Name[0] = 'S':
print(Name)
Answer
The errors in this code are:
- In the list
[Amar, Shveta, Parag]
, each element should be enclosed in quotes because they are strings. - The equality comparison operator is '==' instead of = for checking equality.
- if statement should be lowercase.
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)
:
- The start index
len(words)
is invalid for the listwords
as it will have indexes from 0 tolen(words) - 1
. - 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.
The corrected python code is :
for i in range(len(words)-1, -1, -1):
print(words[i], end=' ')
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
a is: Hello
b is: Nita
c is: How's
d is: life ?
Hi Nita
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"
ntpl[0][0]
and ntpl[1][1]
concatenates to form "Hi". Thus ntpl[0][0]+ntpl[1][1], ntpl[1]
will return "Hi Nita ".
What will be the output of the following code ?
tuple_a = 'a', 'b'
tuple_b = ('a', 'b')
print (tuple_a == tuple_b)
Answer
True
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.
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)
- True
- False
- 1
- Exception
Answer
True
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.
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
dict_items([('name', 'Aman'), ('age', 27), ('address', 'Delhi')])
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')].
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 :")))
Enter the elements of the list separated by spaces:41 DROND GIRIRAJ 13 ZARA
414141
DROND#
GIRIRAJ#
131313
ZARA#
- 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
. - Then splits the input string my_list into individual elements and stores them in a new list called
new_list
. - Then for loop iterates over each element in the new_list.
- 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 '#'.
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.
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
30
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}
- An empty dictionary named
my_dict
is initialized. my_dict[(1,2,4)] = 8, my_dict[(4,2,1)] = 10, my_dict[(1,2)] = 12
these lines assign values to the dictionarymy_dict
with keys as tuples. Since tuples are immutable, so they can be used as keys in the dictionary.- The
for
loop iterates over the keys of the dictionarymy_dict
. Inside the loop, the value associated with each key k is added to the variablesum
. sum
andmy_dict
are printed.
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).
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")
Enter the phone number: 017-555-1212
Valid Phone Number
=====================================
Enter the phone number: 017-5A5-1212
Invalid Phone Number
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.
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
alnumPercent = alnumCount / length * 100
print("Original Sentences:")
print(str)
print("Number of words =", (spaceCount + 1))
print("Number of characters =", (length))
print("Alphanumeric Percentage =", alnumPercent)
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
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].
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)
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]
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.
l = eval(input("Enter the list: "))
print("Original List")
print(l)
l = l[-1:] + l[:-1]
print("Rotated List")
print(l)
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]
Write a short python code segment that prints the longest word in a list of words.
my_list = eval(input("Enter the list : "))
longest_word = ""
max_length = 0
for word in my_list:
if len(word) > max_length:
max_length = len(word)
longest_word = word
print("Longest word:", longest_word)
Enter the list : ['red', 'yellow', 'green', 'blue']
Longest word: yellow
Enter the list : ['lion', 'elephant', 'tiger', 'monkey', 'hippopotamus']
Longest word: hippopotamus
Write a program that creates a list of all the integers less than 100 that are multiples of 3 or 5.
a = []
for i in range(0,100):
if (i % 3 == 0) or (i % 5 == 0) :
a.append(i)
print(a)
[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]
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.
first = "Jimmy"
second = "Johny"
temp = first
first = second
second = temp
print("first =", first)
print("second =", second)
first = Johny
second = Jimmy
Write a python program that creates a tuple storing first 9 terms of Fibonacci series.
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)
9 terms of Fibonacci series are: (0, 1, 1, 2, 3, 5, 8, 13, 21)
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.
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
}
m = input("Enter name of month: ")
if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)
print("Months in alphabetical order are:", sorted(days_in_months))
print("Months with 31 days:", end=" ")
for i in days_in_months:
if days_in_months[i] == 31:
print(i, end=" ")
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)
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}
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.
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
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
result = addDict(dict1, dict2)
print("Union of dict1 and dict2:", result)
Union of dict1 and dict2: {'a': 1, 'b': 3, 'c': 4}
Write a program to sort a dictionary's keys using Bubble sort and produce the sorted keys as a list.
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)
Enter the dictionary: {'c':10, 'f':87, 'r':23, 'a':5}
Sorted keys: ['a', 'c', 'f', 'r']
Write a program to sort a dictionary's values using Bubble sort and produce the sorted values as a list.
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)
Enter the dictionary: {'w':34, 'a':5, 'g':45, 't':21}
Sorted values: [5, 21, 34, 45]