Python Interview Questions & Answers on “Mapping Functions”.
1. What will be the output of the following Python code?
elements = [0, 1, 2] def incr(x): return x+1 print(list(map(elements, incr)))
a) [1, 2, 3]
b) [0, 1, 2]
c) error
d) none of the mentioned
Answer: c
Clarification: The list should be the second parameter to the mapping function.
2. What will be the output of the following Python code?
elements = [0, 1, 2] def incr(x): return x+1 print(list(map(incr, elements)))
a) [1, 2, 3]
b) [0, 1, 2]
c) error
d) none of the mentioned
Answer: a
Clarification: Each element of the list is incremented.
3. What will be the output of the following Python code?
x = ['ab', 'cd'] print(list(map(upper, x)))
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’]
c) error
d) none of the mentioned
Answer: c
Clarification: A NameError occurs because upper is a class method.
4. What will be the output of the following Python code?
def to_upper(k): return k.upper() x = ['ab', 'cd'] print(list(map(upper, x)))
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’]
c) none of the mentioned
d) error
Answer: d
Clarification: A NameError occurs because upper is a class method.
5. What will be the output of the following Python code?
def to_upper(k): return k.upper() x = ['ab', 'cd'] print(list(map(to_upper, x)))
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’]
c) none of the mentioned
d) error
Answer: a
Clarification: Each element of the list is converted to uppercase.
6. What will be the output of the following Python code?
def to_upper(k): k.upper() x = ['ab', 'cd'] print(list(map(to_upper, x)))
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’]
c) none of the mentioned
d) error
Answer: c
Clarification: A list of Nones is printed as to_upper() returns None.
7. What will be the output of the following Python code?
x = ['ab', 'cd'] print(map(len, x))
a) [‘ab’, ‘cd’]
b) [2, 2]
c) [‘2’, ‘2’]
d) none of the mentioned
Answer: d
Clarification: A map object is generated by map(). We must convert this to a list to be able to print it in a human readable form.
8. What will be the output of the following Python code?
x = ['ab', 'cd'] print(list(map(len, x)))
a) [‘ab’, ‘cd’]
b) [2, 2]
c) [‘2’, ‘2’]
d) none of the mentioned
Answer: b
Clarification: The length of each string is 2.
9. What will be the output of the following Python code?
x = ['ab', 'cd'] print(len(map(list, x)))
a) [2, 2]
b) 2
c) 4
d) none of the mentioned
Answer: d
Clarification: A TypeError occurs as map has no len().
10. What will be the output of the following Python code?
x = ['ab', 'cd'] print(len(list(map(list, x))))
a) 2
b) 4
c) error
d) none of the mentioned
Answer: a
Clarification: The outer list has two lists in it. So it’s length is 2.
interview questions on Python,
