Test Series - python

Test Number 49/108

Q: Is the following Python code valid?

>>> a,b,c=1,2,3
>>> a,b,c
A. Yes, [1,2,3] is printed
B. No, invalid syntax
C. Yes, (1,2,3) is printed
D. 1 is printed
Solution: A tuple needn’t be enclosed in parenthesis.
Q: Is the following Python code valid?

>>> a,b=1,2,3
A. Yes, this is an example of tuple unpacking. a=1 and b=2
B. Yes, this is an example of tuple unpacking. a=(1,2) and b=3
C. No, too many values to unpack
D. Yes, this is an example of tuple unpacking. a=1 and b=(2,3)
Solution: For unpacking to happen, the number of values of the right hand side must be equal to the number of variables on the left hand side.
Q: What will be the output of the following Python code?

>>> a=(1,2)
>>> b=(3,4)
>>> c=a+b
>>> c
A. (4,6)
B. (1,2,3,4)
C. Error as tuples are immutable
D. None
Solution: In the above piece of code, the values of the tuples aren’t being changed. Both the tuples are simply concatenated.
Q: What will be the output of the following Python code?

>>> a,b=6,7
>>> a,b=b,a
>>> a,b
A. (6,7)
B. Invalid syntax
C. (7,6)
D. Nothing is printed
Solution: The above piece of code illustrates the unpacking of variables.
Q: Tuples can’t be made keys of a dictionary.
A. True
B. False
C. none
D. ..
Solution: Tuples can be made keys of a dictionary because they are hashable.
Q: Is the following Python code valid?

>>> a=2,3,4,5
>>> a
A. Yes, 2 is printed
B. Yes, [2,3,4,5] is printed
C. No, too many values to unpack
D. Yes, (2,3,4,5) is printed
Solution: A tuple needn’t be enclosed in parenthesis.
Q: What will be the output of the following Python code?

>>> a=(2,3,1,5)
>>> a.sort()
>>> a
A. (1,2,3,5)
B. (2,3,1,5)
C. None
D. Error, tuple has no attribute sort
Solution: A tuple is immutable thus it doesn’t have a sort attribute.
Q: Is the following Python code valid?

>>> a=(1,2,3)
>>> b=a.update(4,)
A. Yes, a=(1,2,3,4) and b=(1,2,3,4)
B. Yes, a=(1,2,3) and b=(1,2,3,4)
C. No because tuples are immutable
D. No because wrong syntax for update() method
Solution: Tuple doesn’t have any update() attribute because it is immutable.

You Have Score    /8