Test Series - python

Test Number 41/108

Q: What will be the output of the following Python code?

a=[10,23,56,[78]]
b=list(a)
a[3][0]=95
a[1]=34
print(b)
A. [10,34,56,[95]]
B. [10,23,56,[78]]
C. [10,23,56,[95]]
D. [10,34,56,[78]]
Solution: The above copy is a type of shallow copy and only changes made in sublist is reflected in the copied list.
Q: What will be the output of the following Python code?

import copy
a=[10,23,56,[78]]
b=copy.deepcopy(a)
a[3][0]=95
a[1]=34
print(b)
A. [10,34,56,[95]]
B. [10,23,56,[78]]
C. [10,23,56,[95]]
D. [10,34,56,[78]]
Solution: The above copy is deepcopy. Any change made in the original list isn’t reflected.
Q: What will be the output of the following Python code?

s="a@b@c@d"
a=list(s.partition("@"))
print(a)
b=list(s.split("@",3))
print(b)
A. [‘a’,’b’,’c’,’d’] [‘a’,’b’,’c’,’d’]
B. [‘a’,’@’,’b’,’@’,’c’,’@’,’d’] [‘a’,’b’,’c’,’d’]
C. [‘a’,’@’,’b@c@d’] [‘a’,’b’,’c’,’d’]
D. [‘a’,’@’,’b@c@d’] [‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
Solution: The partition function only splits for the first parameter along with the separator while split function splits for the number of times given in the second argument but without the separator.
Q: What will be the output of the following Python code?

a=[1,2,3,4]
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print(b)
A. 10
B. [1,3,5,7]
C. 4
D. [1,3,6,10]
Solution: The above code returns the cumulative sum of elements in a list.
Q: What will be the output of the following Python code?

a="hello"
b=list((x.upper(),len(x)) for x in a)
print(b)
A. [(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1)]
B. [(‘HELLO’, 5)]
C. [(‘H’, 5), (‘E’, 5), (‘L’, 5), (‘L’, 5), (‘O’, 5)]
D. Syntax error
Solution: Variable x iterates over each letter in string a hence the length of each letter is 1.
Q: What will be the output of the following Python code?

a=[1,2,3,4]
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print(b)
A. 10
B. [1,3,5,7]
C. 4
D. [1,3,6,10]
Solution: The above code returns the cumulative sum of elements in a list.
Q: What will be the output of the following Python code?

a=[[]]*3
a[1].append(7)
print(a)
A. Syntax error
B. [[7], [7], [7]]
C. [[7], [], []]
D. [[],7, [], []]
Solution: The first line of the code creates multiple reference copies of sublist. Hence when 7 is appended, it gets appended to all the sublists.
Q: What will be the output of the following Python code?

b=[2,3,4,5]
a=list(filter(lambda x:x%2,b))
print(a)
A. [2,4]
B. [ ]
C. [3,5]
D. Invalid arguments for filter function
Solution: The filter function gives value from the list b for which the condition is true, that is, x%2==1.
Q: What will be the output of the following Python code?

lst=[3,4,6,1,2]
lst[1:2]=[7,8]
print(lst)
A. [3, 7, 8, 6, 1, 2]
B. Syntax error
C. [3,[7,8],6,1,2]
D. [3,4,6,7,8]
Solution: In the piece of code, slice assignment has been implemented. The sliced list is replaced by the assigned elements in the list. Type in python shell to verify.

You Have Score    /9