What do you mean by the following terms ?
(i) raw data
(ii) data item
(iii) data type
(iv) data structure
Answer
(i) raw data — Raw data are raw facts. These are simply values or set of values.
(ii) data item — Data item represents single unit of values of certain type.
(iii) data type — A data type defines a set of values along with well-defined operations stating its input-output behaviour.
(iv) data structure — A data structure is a named group of data of different data types which is stored in a specific way and can be processed as a single unit. A data structure has well-defined operations, behaviour and properties.
What do you understand by the following :
(i) simple data structures
(ii) compound data structures
(iii) linear data structures
(iv) non-linear data structures ?
Answer
(i) Simple data structures — Simple data structures are normally built from primitive data types like integers, reals, characters, boolean. For example : Array or Linear lists.
(ii) Compound data structures — Compound data structures are formed by combination of Simple data structures. The compound data structures may be linear (a single sequence) and non-linear (multi-level).
(iii) Linear data structures — A data structure is said to be linear if its elements form a sequence or linear list. These data structures are single level data structures. For example: Arrays.
(iv) Non-linear data structures — A data structure is said to be non-linear if traversal of nodes is nonlinear in nature. These are multilevel data structures. For example: Tree.
When would you go for linear search in an array and why?
Answer
If the array is unsorted and the number of elements in the array are less then we should prefer linear search because the overhead of sorting the array will be more than traversing the complete array for finding the required element.
State condition(s) when binary search is applicable.
Answer
The conditions when binary search is applicable are as follows:
- Binary search can only work for sorted arrays.
- Binary search is most effective when random access to elements is available.
- Binary search is advantageous when the array size is large.
- Binary search is useful for saving time and number of comparisons.
Name the efficient algorithm offered by Python to insert element in a sorted sequence.
Answer
insort()
function of bisect
module in Python.
What is a list comprehension ?
Answer
A list comprehension is a concise description of a list that shorthands the list creating for loop in the form of a single statement. The syntax is: [expression_creating_list for (set of values) condition]
.
What is a 2D list ?
Answer
A two dimensional list is a list having all its elements as lists of same shapes, i.e., a two dimensional list is a list of lists.
What is a nested list ?
Answer
A list that has one or more lists as its elements is a nested list.
Is Ragged list a nested list ?
Answer
Yes, ragged lists are nested lists. A list that has one or more lists as its elements, with each element-list having a different length, is known as a ragged list.
What will be the output of the following Python code ?
a = [10,23,56,[78, 10]]
b = list(a)
a[3][0] += 17
print(b)
- [10, 23, 71, [95, 10]]
- [10, 23, 56, [78, 25]]
- [10, 23, 56, [95, 10]]
- [10, 34, 71, [78, 10]]
Answer
[10, 23, 56, [95, 10]]
Reason —
a = [10, 23, 56, [78, 10]]
— This creates a nested lista
.b = list(a)
— This creates a shallow copy ofa
and assigns it tob
. The listb
references to the same objects asa
.a[3][0] += 17
—a[3]
accesses the sublist at index 3, i.e., [78, 10], and[0]
further accesses the first element of that sublist, i.e., 78. Then, it adds 17 to 78, changing it to 95.print(b)
— This prints the contents of listb
. Sinceb
is a shallow copy ofa
, any changes made to the nested list withina
will also reflect inb
. Therefore, when we printb
, we'll see the modified value [95, 10].
What will be the output of the following Python code ?
lst1 = "hello"
lst2 = list((x.upper(), len(x)) for x in lst1)
print(lst2)
- [('H', 1), ('E', 1), ('L',1), ('L',1), ('O', 1)]
- [('HELLO', 5)]
- [('H',5), ('E', 5), ('L',5), ('L',5), ('O', 5)]
- Syntax error
Answer
[('H', 1), ('E', 1), ('L',1), ('L',1), ('O', 1)]
Reason —
lst1 = "hello"
— This line initializes a string variablelst1
with the value "hello".lst2 = list((x.upper(), len(x)) for x in lst1)
— This line is a list comprehension, which iterates over each characterx
in the stringlst1
. For each characterx
, it creates a tuple containing two elements:
(a) The uppercase version of the characterx
, obtained using theupper()
method.
(b) The length of the characterx
, obtained using thelen()
function.
These tuples are collected into a list, which is assigned to the variablelst2
.print(lst2)
— This line prints the listlst2
.
What will be the output of the following Python code ?
lst = [3, 4, 6, 1, 2]
lst[1:2] = [7,8]
print(lst)
- [3, 7, 8, 6, 1, 2]
- Syntax error
- [3, [7, 8], 6, 1, 2]
- [3, 4, 6, 7, 8]
Answer
[3, 7, 8, 6, 1, 2]
Reason —
lst = [3, 4, 6, 1, 2]
— This line initializes a list variablelst
with the values [3, 4, 6, 1, 2].lst[1:2] = [7,8]
—lst[1:2]
refers to a slice of listlst
at index 1. It replaces this slice with the values from the list[7, 8]
. Nowlst
becomes[3, 7, 8, 6, 1, 2]
.
(If we change this line tolst[1] = [7, 8]
, then output would be[3, [7, 8], 6, 1, 2]
because it would replace the entire element at index 1 (i.e., 4) with[7, 8]
.)print(lst)
— This line prints the modified listlst
.
What will be the output of the following Python code snippet ?
k = [print(i) for i in my_string if i not in "aeiou"]
- prints all the vowels in my_string
- prints all the consonants in my_string
- prints all characters of my_string that aren't vowels
- prints only on executing print(k)
Answer
prints all characters of my_string that aren't vowels
Reason — The expression [print(i) for i in my_string if i not in "aeiou"]
is a list comprehension that iterates over each character i
in the string my_string
. It checks if the character i
is not a vowel (i.e., it's not in the string "aeiou"). If i
is not a vowel, it prints the character i
.
Which of the following is the correct expansion of list_1 = [expr(i) for i in list_0 if func(i)] ?
(a)
list_1 = []
for i in list_0:
if func(i):
list_1.append(i)
(b)
for i in list_0:
if func(i):
list_1.append(expr(i))
(c)
list_1 = []
for i in list_0:
if func(i):
list_1.append(expr(i))
(d) none of these
Answer
list_1 = []
for i in list_0:
if func(i):
list_1.append(expr(i))
Reason —
for i in list_0
— This part iterates over each elementi
in the listlist_0
.if func(i)
— This part applies the functionfunc()
to each elementi
and checks if the result is True. Only elements for whichfunc(i)
returns True will be included in the resulting list.expr(i)
— This part applies some expression or function callexpr()
to each selected elementi
.
Therefore, the correct expansion would be:
list_1 = []
for i in list_0:
if func(i):
list_1.append(expr(i))
A data structure is a named group of data of different data types which can be processed as a single unit.
In linear search, each element of the list is compared with the given item to be reached for, one-by-one.
A list comprehension is a concise description of a list creation for loop.
A nested list has lists as its elements.
A regular nested list has same shape of all its element-lists.
2D lists can only contain lists of same shapes.
Answer
False
Reason — 2D lists can contain lists of the same shape, known as regular 2D lists, and can also contain lists of different shapes, known as ragged lists.
Stacks can be implemented using lists.
Answer
True
Reason — Stack data structure refers to the list stored and accessed in a special way, where LIFO (Last In First Out) technique is followed.
Lists where controlled insertions and deletions take place such that insertions at the rear end and deletions from the front end, are queues.
Answer
True
Reason — Queues data structures are FIFO (First In First Out) lists, where insertions take place at the "rear" end of the queues and deletions take place at the "front" end of the queues.
A ragged list has same shape of all its elements.
Answer
False
Reason — A list that has one or more lists as its elements, with each element-list having a different shape, i.e., a different number of elements, is known as a ragged list.
A regular 2D list has same shape of all its elements.
Answer
True
Reason — A regular two dimensional list is a list having lists as its elements and each element-list has the same shape i.e., same number of elements (length).
Assertion. A linear list refers to a named list of finite number of similar data elements.
Reason. Similar type of elements grouped under one name make a linear list.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
A linear list consists of a finite number of homogeneous data elements, i.e., data elements of the same data type, arranged in a sequential manner under one name.
Assertion. A list having one or more lists as its elements is called a nested list.
Reason. Two or more lists as part of another data structure such as dictionaries or tuples, create nested lists.
Answer
(b)
Both Assertion and Reason are true but Reason is not the correct explanation of Assertion.
Explanation
A nested list is a list having one or more lists as its elements. Nested lists can be elements within other data structures like dictionaries or tuples. But nested lists can exist independently and are commonly used in Python programming to represent multi-dimensional lists.
Assertion. A list having same-sized lists as its elements is a regular 2D list.
Reason. When similar sequences such as tuples, dictionaries and lists become part of another data structure, they make a regular 2D list.
Answer
(b)
Both Assertion and Reason are true but Reason is not the correct explanation of Assertion.
Explanation
A regular two dimensional list is a list having lists as its elements and each element-list has the same number of elements. Regular 2D lists do not necessarily depend on being nested within other data structures such as tuples or dictionaries because regular 2D lists can exist independently as data structures in Python.
Assertion. A list having lists as its elements with elements being different-shaped make a ragged 2D list.
Reason. A list having different-sized lists as its elements make an irregular 2D list.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
A list that has lists as its elements, with each element-list having a different shape, i.e., a different number of elements, is a ragged 2D list, also known as an irregular 2D list.
What are data structures ? Name some common data structures.
Answer
A data structure is a named group of data of different data types which is stored in a specific way and can be processed as a single unit. A data structure has well-defined operations, behaviour and properties.
Some common data structures are Stack, Lists, Queue, Linked lists and Tree.
Is data structure related to a data type ? Explain.
Answer
Yes, data structures are related to data types, but they are distinct concepts. A data type is a set of values with well-defined operations dictating its input-output behavior e.g., two strings cannot be multiplied. While a data structure is a named group of data of different data types stored in a specific way, capable of being processed as a single unit e.g., lists, arrays, stack. A data structure possesses well-defined operations, behavior, and properties. Data structures not only allow users to combine various data types into a group but also enable processing of the group as a single unit, thereby making things much simpler and easier.
What do you understand by linear and non-linear data structures ?
Answer
Linear data structures — A data structure is said to be linear if its elements form a sequence. These data structures are single level data structures. For example: Stack, Queue, Linked List.
Non-linear data structures — These data structures are multilevel data structures having a hierarchical relationship among its elements called nodes. For example: Tree
Name some linear data structures. Is linked list a linear data structure ?
Answer
Stack, queue and linked list are linear data structures. Yes, a linked list is a linear data structure. Linked lists consist of a sequence of elements, each containing a reference to the next element in the sequence, forming a linear arrangement.
What is the working principle of data structures stack and queues ?
Answer
The working principle of a stack follows the Last In First Out (LIFO) technique, where insertions and deletions occur at one end, known as the top. Elements are added to and removed from the top of the stack, allowing the most recently added item to be accessed first.
The working principle of a queue follows the First In First Out (FIFO) technique, where insertions are made at one end, known as the rear, and deletions occur at the other end, known as the front. This ensures that the oldest elements in the queue are processed first, similar to waiting in a line or queue.
What is a linear list data structure ? Name some operations that you can perform on linear lists.
Answer
A linear list data structure is a list of finite number of data elements of the same data type arranged in a sequential manner under one name. The operations that we can perform on linear lists are as follows:
- Insertion
- Deletion
- Searching
- Traversal
- Sorting
- Merging
Suggested situations where you can use these data structures:
(i) linear lists
(ii) stacks
(iii) queues
Answer
(i) Linear lists — Linear lists are utilized when storing and managing collections of data elements in a sequential manner is necessary. For example, managing a list of student records in a university database.
(ii) Stacks — Stacks are used when data needs to be managed based on the Last In, First Out (LIFO) principle. For example, function call management in programming languages employs a stack structure to store and manage function calls.
(iii) Queues — Queues are used when data needs to be managed based on the First In, First Out (FIFO) principle. For example, a print spooling system, where print jobs are queued in the order they were received.
What is a list comprehension ? How is it useful ?
Answer
A list comprehension is a concise description of a list that shorthands the list creating for loop in the form of a single statement. The syntax is:
[expression_creating_list for (set of values to iterate upon) condition]
List comprehensions make code compact, more readable, more efficient and are faster to execute.
Enlist some advantages of list comprehensions.
Answer
Advantages of list comprehensions are as follows:
- Code reduction — A code of 3 or more lines (for loop with or without a condition) gets reduced to a single line of code.
- Faster code processing — List comprehensions are executed faster than their equivalent for loops for these two reasons:
- Python will allocate the list's memory first, before adding the elements to it, instead of having to resize on runtime.
- Also, calls to append() function get avoided, reducing function overhead time (i.e., additional time taken to call and return from a function).
In which situations should you use list comprehensions and in which situations you should not use list comprehensions ?
Answer
List comprehensions are used in situations where we need to perform simple operations on iterable data structures, leading to more readable and compact code. List comprehensions are commonly used for tasks such as generating sequences, mapping elements of a list, filtering elements based on certain criteria, and combining elements from multiple iterables.
List comprehensions should not be used when we need to check multiple conditions.
What is a nested list ? Give some examples.
Answer
A list that has one or more lists as its elements is a nested list.
For example: a = [11, [2, 23]], b = [[11, 3], [5, 6], [9, 8]]
What is a two dimensional list ? How is it related to nested lists ?
Answer
A two dimensional list is a list having all its elements as lists of same shapes, i.e., a two dimensional list is a list of lists. A two dimensional list is also a nested list, as it involves nesting one list inside another.
Suggest a situation where you can use a regular two dimensional list.
Answer
A regular two dimensional list is used where structured data organization is required. For example, a program to store and manipulate student grades. We can use a two-dimensional list where each row represents a student and each column represents a different subject.
What are ragged lists ? How are these different from two dimensional lists ?
Answer
A list that has lists as its elements, with each element-list having a different shape, i.e., a different number of elements, is a ragged list. These are also two dimensional lists but irregular 2D lists. So, the main difference between ragged lists and two-dimensional lists is that ragged lists have inner lists with varying lengths, while two-dimensional lists have inner lists with the same lengths, resulting in a regular structure.
Suggest a situation where you can use ragged list ?
Answer
Suppose we are building a program to store information about different families and their members. In this program, each family can have a variable number of members, making it suitable to use a ragged list.
How are lists internally stored ? How are 2D lists internally stored ?
Answer
Lists in Python are stored similarly to strings in memory. However, lists store references to their elements at each index, which can vary in size. This means that each index of a list holds a reference to the actual object stored elsewhere in memory. Each of the individual items in the list occupies its own memory location.
When it comes to 2D lists, also known as lists of lists, they follow a similar principle. Internally, a 2D list is represented as an array of pointers to inner lists. Each element of the outer list is a reference to an inner list object, which in turn is another array of pointers to the elements it contains.
Create a list SqLst that stores the doubles of elements of another list NumLst. Following code is trying to achieve this. Will this code work as desired ? What will be stored in SqLst after following code ?
NumLst = [2, 5, 1, 7, 3, 6, 8, 9]
SqLst = NumLst * 2
Answer
No, the above code will not work as desired.
[2, 5, 1, 7, 3, 6, 8, 9, 2, 5, 1, 7, 3, 6, 8, 9] will be stored in SqLst after the above code is executed. The multiplication operator * with a list NumLst
, duplicates the elements of the list NumLst
by 2 times.
The correct code is:
NumLst = [2, 5, 1, 7, 3, 6, 8, 9]
SqLst = []
for num in NumLst:
SqLst.append(num * 2)
print(SqLst)
[4, 10, 2, 14, 6, 12, 16, 18]
Change the above code so that it works as stated in previous question.
Answer
NumLst = [2, 5, 1, 7, 3, 6, 8, 9]
SqLst = []
for num in NumLst:
SqLst.append(num * 2)
print(SqLst)
[4, 10, 2, 14, 6, 12, 16, 18]
NumLst = [2, 5, 1, 7, 3, 6, 8, 9]
— This line creates a list calledNumLst
containing the given numbers [2, 5, 1, 7, 3, 6, 8, 9].SqLst = []
— This line initializes an empty list calledSqLst
.for num in NumLst:
— This line starts afor
loop that iterates over each elementnum
in theNumLst
list.SqLst.append(num * 2)
— Inside the loop, eachnum
is multiplied by 2, and the result is appended to theSqLst
list.print(SqLst)
— This line prints the resulting listSqLst
.
Modify your previous code so that SqLst stores the doubled numbers in ascending order.
Answer
NumLst = [2, 5, 1, 7, 3, 6, 8, 9]
SqLst = []
for num in NumLst:
SqLst.append(num * 2)
n = len(SqLst)
for i in range(n):
for j in range(0, n-i-1):
if SqLst[j] > SqLst[j+1]:
SqLst[j], SqLst[j+1] = SqLst[j+1], SqLst[j]
print(SqLst)
[2, 4, 6, 10, 12, 14, 16, 18]
Consider a list ML = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write code using a list comprehension that takes the list ML and makes a new list that has only the even elements of this list in it.
Answer
ML = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
A = [i for i in ML if i % 2 == 0]
print(A)
[4, 16, 36, 64, 100]
ML = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
— This line initializes a listML
.A = [i for i in ML if i % 2 == 0]
— This line uses a list comprehension to create a new listA
. It iterates over each elementi
in the listML
, and only includesi
inA
if i % 2 == 0 is true. This condition checks if the elementi
is even.print(A)
— This line prints the list A, which contains only the even numbers from the listML
.
Write equivalent list comprehension for the following code :
target1 = []
for number in source:
if number & 1:
target1.append(number)
Answer
target1 = [number for number in source if number & 1]
Write equivalent for loop for the following list comprehension :
gen = (i/2 for i in [0, 9, 21, 32])
print(gen)
Answer
In the above code, Python would raise an error because round brackets are used in list comprehension. List comprehensions work with square brackets only.
The corrected code is:
gen = [i/2 for i in [0, 9, 21, 32]]
print(gen)
The equivalent for loop for the above list comprehension is:
gen = []
for i in [0, 9, 21, 32]:
gen.append(i/2)
print(gen)
Predict the output of following code if the input is :
(i) 12, 3, 4, 5, 7, 12, 8, 23, 12
(ii) 8, 9, 2, 3, 7, 8
Code :
s = eval(input("Enter a list : "))
n = len(s)
t = s[1:n-1]
print(s[0] == s[n-1] and
t.count(s[0]) == 0)
Answer
Enter a list : [12, 3, 4, 5, 7, 12, 8, 23, 12]
False
Enter a list : [8, 9, 2, 3, 7, 8]
True
s = eval(input("Enter a list : "))
— This line prompts the user to enter a list.n = len(s)
— This line finds the length of the lists
.t = s[1:n-1]
— This line slices the lists
starting from index 1 up to index n-1, which effectively removes the first and last elements from the lists
and stores it in listt
.print(s[0] == s[n-1] and t.count(s[0]) == 0)
— The conditions[0] == s[n-1] and t.count(s[0]) == 0
checks if the first and the last element of the lists
are same [s[0] == s[n-1]
] and that element does not appear anywhere else in lists
apart from the first and last position [t.count(s[0]) == 0
]. For case (i), 12 is the first and the last element of list but as it also occurs at the 5th index hence the output isFalse
. For case (ii), 8 is the first and the last element of list and it doesn't appear anywhere else hence the output isTrue
.
Predict the output :
def h_t(NLst):
from_back = NLst.pop()
from_front = NLst.pop(0)
NLst.append(from_front)
NLst.insert(0, from_back)
NLst1 = [[21, 12], 31]
NLst3 = NLst1.copy()
NLst2 = NLst1
NLst2[-1] = 5
NLst2.insert(1, 6)
h_t(NLst1)
print(NLst1[0], NLst1[-1], len(NLst1))
print(NLst2[0], NLst2[-1], len(NLst2))
print(NLst3[0], NLst3[-1], len(NLst3))
Answer
5 [21, 12] 3
5 [21, 12] 3
[21, 12] 31 2
def h_t(NLst):
— This line defines a function namedh_t
that takes a single argumentNLst
.from_back = NLst.pop()
— This line removes and returns the last element from the listNLst
, storing it in the variablefrom_back
.from_front = NLst.pop(0)
— This line removes and returns the first element from the listNLst
, storing it in the variablefrom_front
.NLst.append(from_front)
— This line appends the value stored infrom_front
to the end of the listNLst
.NLst.insert(0, from_back)
— This line inserts the value stored infrom_back
at the beginning of the listNLst
.NLst1 = [[21, 12], 31]
— This line initializesNLst1
as a nested list.NLst3 = NLst1.copy()
— This line creates a shallow copy ofNLst1
and assigns it toNLst3
.NLst2 = NLst1
— This line assigns the reference ofNLst1
toNLst2
, meaning bothNLst1
andNLst2
point to the same list object.NLst2[-1] = 5
— This line modifies the last element ofNLst2
to 5. SinceNLst1
andNLst2
reference the same list object, this change also affectsNLst1
.NLst2.insert(1, 6)
— This line inserts 6 at index 1 inNLst2
. Again, sinceNLst1
andNLst2
reference the same list object, this change also affectsNLst1
.h_t(NLst1)
— This line calls the functionh_t
withNLst1
as an argument.print(NLst1[0], NLst1[-1], len(NLst1))
— This line prints the first element, last element, and length ofNLst1
.print(NLst2[0], NLst2[-1], len(NLst2))
— This line prints the first element, last element, and length ofNLst2
.print(NLst3[0], NLst3[-1], len(NLst3))
— This line prints the first element, last element, and length ofNLst3
.
Predict the output :
ages = [11, 14, 15, 17, 13, 18, 25]
print(ages)
Elig = [x for x in ages if x in range(14, 18)]
print(Elig)
Answer
The above code will raise an error due to an indentation error in line 2.
The correct code is:
ages = [11, 14, 15, 17, 13, 18, 25]
print(ages)
Elig = [x for x in ages if x in range(14, 18)]
print(Elig)
[11, 14, 15, 17, 13, 18, 25]
[14, 15, 17]
ages = [11, 14, 15, 17, 13, 18, 25]
— This line initializes a listages
.print(ages)
— This line prints the listages
.Elig = [x for x in ages if x in range(14, 18)]
— This line uses list comprehension to create new listElig
, by taking the values between 14 to 17 fromages
list.print(Elig)
— This line prints the listElig
.
Predict the output :
L1= [x ** 2 for x in range(10) if x % 3 == 0]
L2 = L1
L1.append(len(L1))
print(L1)
print(L2)
L2.remove(len(L2) - 1)
print(L1)
Answer
[0, 9, 36, 81, 4]
[0, 9, 36, 81, 4]
[0, 9, 36, 81]
L1 = [x ** 2 for x in range(10) if x % 3 == 0]
— This line creates a listL1
containing the squares of multiples of 3 between 0 to 9.L2 = L1
— This line assigns listL1
to listL2
, meaning bothL1
andL2
reference the same list in memory (shallow copy).L1.append(len(L1))
— This line appends the length ofL1
toL1
. So, the length ofL1
is 4, and it appends 4 toL1
.print(L1)
— This prints the modifiedL1
list.print(L2)
— This printsL2
, which is pointing to the same list asL1
.L2.remove(len(L2) - 1)
— This line removes the last element ofL2
sincelen(L2) - 1
gives the last index ofL2
.print(L1)
— This printsL1
again. Since bothL1
andL2
reference the same list, modifyingL2
also affectsL1
. Therefore,L1
also reflects the change made toL2
.
Predict the output :
def even(n):
return n % 2 == 0
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ev = [n for n in list1 if n % 2 == 0]
evp = [n for n in list1 if even(n)]
print(evp)
Answer
[2, 4, 6, 8]
def even(n)
— This line defines a function namedeven
that takes a parametern
.return n % 2 == 0
— This line returns True if the input numbern
is even (i.e., when n % 2 equals 0), and False otherwise.list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
— This line initializes a list namedlist1
with integers from 1 to 9.ev = [n for n in list1 if n % 2 == 0]
— This line creates a new listev
using a list comprehension. It iterates over each elementn
inlist1
and includesn
inev
if it's even (i.e., if n % 2 == 0).evp = [n for n in list1 if even(n)]
— This line creates a new listevp
using a list comprehension. It iterates over each elementn
inlist1
and includesn
inevp
if the functioneven(n)
returns True for thatn
. Effectively, this also creates a new list from the even numbers oflist1
. Therefore, bothev
andevp
will contain same values.print(evp)
— This line prints the listevp
.
Predict the output.
b = [[9, 6], [4, 5], [7, 7]]
x = b[:2]
x.append(10)
print(x)
Answer
[[9, 6], [4, 5], 10]
b = [[9, 6], [4, 5], [7, 7]]
— This line initializes a listb
containing three sublists, each containing two elements.x = b[:2]
— This line creates a new listx
by slicing the listb
from index 0 to index 1. So,x
will contain the first two sublists ofb
. At this point,x
will be[[9, 6], [4, 5]]
.x.append(10)
— This line appends the integer 10 to the end of the listx
.x
now becomes[[9, 6], [4, 5], 10]
.print(x)
— This line prints the listx
.
Predict the output.
b = [[9, 6], [4, 5], [7, 7]]
x = b[:2]
x[1].append(10)
print(x)
Answer
[[9, 6], [4, 5, 10]]
b = [[9, 6], [4, 5], [7, 7]]
— This line initializes a listb
containing three sublists, each containing two elements.x = b[:2]
— This line creates a new listx
by slicing the listb
from index 0 to index 1. So,x
will contain the first two sublists ofb
. At this point,x
will be[[9, 6], [4, 5]]
.x[1].append(10)
— This line accesses the second sublist ofx
, which is[4, 5]
, and appends 10 at its end. Nowx
becomes[[9, 6], [4, 5, 10]]
print(x)
— This line prints the listx
.
Find the Error. Consider the following code, which runs correctly at times but gives error at other times. Find the error and its reason.
Lst1 = [23, 34, 12, 77, 34, 26, 28, 93, 48, 69, 73, 23, 19, 88]
Lst2 = []
print("List1 originally is: ", Lst1)
ch = int(input("Enter 1/2/3 and \
predict which operation was performed?"))
if ch == 1:
Lst1.append(100)
Lst2.append(100)
elif ch == 2:
print(Lst1.index(100))
print(Lst2.index(100))
elif ch == 3:
print(Lst1.pop())
print(Lst2.pop())
Answer
Lst1 = [23, 34, 12, 77, 34, 26, 28, 93, 48, 69, 73, 23, 19, 88]
Lst2 = []
print("List1 originally is: ", Lst1)
ch = int(input("Enter 1/2/3 and \
predict which operation was performed?"))
if ch == 1:
Lst1.append(100)
Lst2.append(100)
elif ch == 2:
print(Lst1.index(100)) # Error 1
print(Lst2.index(100)) # Error 2
elif ch == 3:
print(Lst1.pop())
print(Lst2.pop()) # Error 3
When the user selects option 1 (ch == 1), the code works correctly, i.e., it appends 100 to both Lst1 and Lst2 at the end. However, errors occur when the user selects option 2 (ch == 2) or option 3 (ch == 3). The errors are as follows:
- Error 1 — Attempting to find the index of 100 in the list
Lst1
usingLst1.index(100)
, an error occurs because 100 is not present inLst1
. - Error 2 — Attempting to find the index of 100 in the list
Lst2
usingLst2.index(100)
, an error occurs because 100 is not present inLst2
. - Error 3 — Attempting to remove an item from an empty list
Lst2
usingLst2.pop()
, an error occurs because there are no items to remove.
Suggest the correction for the error(s) in previous question's code.
Answer
- For the case of finding the index of 100 in
Lst1
andLst2
, we can use conditional checks to verify if 100 is present in each list before attempting to find its index. If 100 is not found, we print an error message. - For the case of popping elements from
Lst2
, we use conditional checks to verify if the list is empty before attempting to pop elements. If a list is empty, we print an error message indicating that popping is not possible.
The corrected code is :
Lst1 = [23, 34, 12, 77, 34, 26, 28, 93, 48, 69, 73, 23, 19, 88]
Lst2 = []
print("List1 originally is: ", Lst1)
ch = int(input("Enter 1/2/3 and predict which operation was performed? "))
if ch == 1:
Lst1.append(100)
Lst2.append(100)
elif ch == 2:
if 100 in Lst1:
print("Index of 100 in Lst1:", Lst1.index(100))
else:
print("Error: 100 is not in Lst1")
if 100 in Lst2:
print("Index of 100 in Lst2:", Lst2.index(100))
else:
print("Error: 100 is not in Lst2")
elif ch == 3:
print(Lst1.pop())
if Lst2:
Lst2.pop()
else:
print("Error: Cannot pop from an empty list (Lst2)")
Find the error. Consider the following code and predict the error(s):
y for y in range(100) if y % 2 == 0 and if y % 5 == 0
Answer
- The list comprehensions should be enclosed in square brackets.
- The code contains a syntax error as it is using two
if
statements within the list comprehension. We should use a singleif
statement with both conditions combined using theand
operator.
Find the error. Consider the following code and predict the error(s):
(y for y in range(100) if y % 2 == 0 and if y % 5 == 0)
Answer
- In the code, round brackets are used for list comprehensions, but list comprehensions work with square brackets only.
- The syntax error arises from the use of two
if
statements within the list comprehension. To resolve this error, we should use a singleif
statement with both conditions combined using theand
operator.
Find the error in the following list comprehension :
["good" if i < 3: else: "better" for i in range(6)]
Answer
The code contains a syntax error due to the placement of the colon (:). There should not be colon in list comprehension.
Suggest corrections for the errors in both the previous questions.
Answer
(i)
y for y in range(100) if y % 2 == 0 and if y % 5 == 0
The list comprehension should be enclosed in square brackets, and we should use a single if
statement with both conditions combined using the and
operator.
The corrected code is:
[y for y in range(100) if y % 2 == 0 and y % 5 == 0]
(ii)
(y for y in range(100) if y % 2 == 0 and if y % 5 == 0)
The list comprehension should be enclosed in square brackets, and we should use a single if
statement with both conditions combined using the and
operator.
The corrected code is:
[y for y in range(100) if y % 2 == 0 and y % 5 == 0]
(iii)
["good" if i < 3: else: "better" for i in range(6)]
The list comprehension does not include colon.
The corrected code is:
["good" if i < 3 else "better" for i in range(6)]
Write a program that uses a function called find_in_list() to check for the position of the first occurrence of v in the list passed as parameter (lst) or -1 if not found. The header for the function is given below :
def find_in_list(lst, v):
""" lst - a list
v - a value that may or
may not be in the list """
def find_in_list(lst, v):
if v in lst:
return lst.index(v)
else:
return -1
lst = eval(input("Enter a list : "))
v = int(input("Enter a value to be checked: "))
print(find_in_list(lst, v))
Enter a list : [1, 2, 4, 7, 2, 55, 78]
Enter a value to be checked: 2
1
Enter a list : [10, 30, 54, 58, 22]
Enter a value to be checked: 22
4
Enter a list : [9, 5, 3, 33]
Enter a value to be checked: 10
-1
Implement the following function for a linear list, which find outs and returns the number of unique elements in the list
def unique(lst):
"""passed parameter lst is a list of
integers (could be empty)."""
After implementing the above function, test it with following lists and show the output produced by above function along with the reason for that output.
(i) lst = []
(ii) lst = [1, 2, 3]
(iii) lst = [1, 2, 2]
(iv) lst = [1, 2, 2, 3, 3]
Answer
def unique(lst):
c = 0
for i in range(0, len(lst)):
if lst[i] not in lst[i+1:]:
c += 1
return c
lst = eval(input("Enter the list: "))
print(unique(lst))
Enter the list: []
0
Enter the list: [1, 2, 3]
3
Enter the list: [1, 2, 2]
2
Enter the list: [1, 2, 2, 3, 3]
3
(i) lst = [] — The output is 0 because the list is empty.
(ii) lst = [1, 2, 3] — The output is 3 because the list contains 3 unique elements — 1, 2, 3.
(iii) lst = [1, 2, 2] — The output is 2 because the list contains 2 unique elements — 1, 2.
(iv) lst = [1, 2, 2, 3, 3] — The output is 3 because the list contains 3 unique elements — 1, 2, 3.
Use a list comprehension to create a list, CB4. The comprehension should consist of the cubes of the numbers 1 through 10 only if the cube is evenly divisible by four. Finally, print that list to the console. Note that in this case, the cubed number should be evenly divisible by 4, not the original number.
CB4 = [x**3 for x in range(1, 11) if (x**3) % 4 == 0]
print(CB4)
[8, 64, 216, 512, 1000]
Take two lists, say for example these two :
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write this in one line of Python using at least one list comprehension. Run the complete program and show output.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = [a[i] for i in range(len(a)) if a[i] in b and a[i] not in a[i+1:]]
print (c)
[1, 2, 3, 5, 8, 13]
Suppose we have a list V where each element represents the visit dates for a particular patient in the last month. We want to calculate the highest number of visits made by any patient. Write a function MVisit(Lst) to do this.
A sample list (V) is shown below :
V = [[2, 6], [3, 10], [15], [23], [1, 8, 15, 22, 29], [14]]
For the above given list V, the function MVisit() should return the result as [1, 8, 15, 22, 29].
def MVisit(Lst):
max_index = 0
for i in range(1, len(Lst)):
if len(Lst[i]) > len(Lst[max_index]):
max_index = i
return Lst[max_index]
V = [[2, 6], [3, 10], [15], [23], [1, 8, 15, 22, 29], [14]]
result = MVisit(V)
print(result)
[1, 8, 15, 22, 29]