Test Series - python

Test Number 42/108

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

a=[1,2,3]
b=a.append(4)
print(a)
print(b)
A. [1,2,3,4] [1,2,3,4]
B. [1, 2, 3, 4] None
C. Syntax error
D. [1,2,3] [1,2,3,4]
Solution: Append function on lists doesn’t return anything. Thus the value of b is None.
Q: What will be the output of the following Python code?

>>> a=[14,52,7]
>>>> b=a.copy()
>>> b is a
A. True
B. False
C. ...
D. ...
Solution: List b is just a copy of the original list. Any copy made in list b will not be reflected in list a.
Q: What will be the output of the following Python code?

a=[13,56,17]
a.append([87])
a.extend([45,67])
print(a)
A. [13, 56, 17, [87], 45, 67]
B. [13, 56, 17, 87, 45, 67]
C. [13, 56, 17, 87,[ 45, 67]]
D. [13, 56, 17, [87], [45, 67]]
Solution: The append function simply adds its arguments to the list as it is while extend function extends its arguments and later appends it.
Q: What is the output of the following piece of code?

a=list((45,)*4)
print((45)*4)
print(a)
A. 180 [(45),(45),(45),(45)]
B. (45,45,45,45) [45,45,45,45]
C. 180 [45,45,45,45]
D. Syntax error
Solution: (45) is an int while (45,) is a tuple of one element. Thus when a tuple is multiplied, it created references of itself which is later converted to a list.
Q: What will be the output of the following Python code?

lst=[[1,2],[3,4]]
print(sum(lst,[]))
A. [[3],[7]]
B. [1,2,3,4]
C. Error
D. [10]
Solution: The above piece of code is used for flattening lists.
Q: What will be the output of the following Python code?

word1="Apple"
word2="Apple"
list1=[1,2,3]
list2=[1,2,3]
print(word1 is word2)
print(list1 is list2)
A. True True
B. False True
C. False False
D. True False
Solution: In the above case, both the lists are equivalent but not identical as they have different objects.
Q: What will be the output of the following Python code?

def unpack(a,b,c,d):
    print(a+d)
x = [1,2,3,4]
unpack(*x)
A. Error
B. [1,4]
C. [5]
D. 5
Solution: unpack(*x) unpacks the list into the separate variables. Now, a=1 and d=4. Thus 5 gets printed.
Q: What will be the output of the following Python code?

x=[[1],[2]]
print(" ".join(list(map(str,x))))
A. [1] [2]
B. [49] [50]
C. Syntax error
D. [[1]] [[2]]
Solution: The elements 1 and 2 are first put into separate lists and then combined with a space in between using the join attribute.
Q: What will be the output of the following Python code?

a=165
b=sum(list(map(int,str(a))))
print(b)
A. 561
B. 5
C. 12
D. Syntax error
Solution: First, map converts the number to string and then places the individual digits in a list. Then, sum finds the sum of the digits in the list. The code basically finds the sum of digits in the number.

You Have Score    /9