Thursday 7 April 2022

Python Comprehensions Interview questions - Multiple choice

 1. Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is:

a) [0, 1, 2, 3]

b) [0, 1, 2, 3, 4]

c) [0.0, 0.5, 1.0, 1.5]

d) [0.0, 0.5, 1.0, 1.5, 2.0]


Answer: c

Explanation: Execute in the shell to verify.


2. What will be the output of the following Python code?

names_1 = ["Narendra", "Bhagyasree", "Raj", "Mahalakshmi"]

names_2 = [name.lower() for name in names_1]

 print(names_2[2][0])

a) None

b) R

c) r

d) b


Answer: c

Explanation: List Comprehension is a shorthand for creating new lists.


3. What will be the output of the following Python code?

>>>m = [[x, x + 1, x + 2] for x in range(0, 3)]

a) [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

b) [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

c) [1, 2, 3, 4, 5, 6, 7, 8, 9]

d) [0, 1, 2, 1, 2, 3, 2, 3, 4]


Answer: b

Explanation: Execute in the shell to verify.


4. How many elements are in m?

m = [[x, y] for x in range(0, 4) for y in range(0, 4)]

a) 8

b) 12

c) 16

d) 32


Answer: c

Explanation: Execute in the shell to verify.

 

5. 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]


Answer: d

Explanation: The above code returns the cumulative sum of elements in a list


6. What will be the output of the following Python code?

>>>t = (1, 2, 4, 3, 8, 9)

>>>[t[i] for i in range(0, len(t), 2)]

a) Error

b) [1, 2, 4, 3, 8, 9]

c) [1, 4, 8]

d) (1, 4, 8)


Answer: c

Explanation: Execute in the shell to verify.


7. What will be the output of the following Python code?

a={i: i*i for i in range(6)}

print(a)

a) Dictionary comprehension doesn’t exist

b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36}

c) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25}

d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}


Answer: d

Explanation: Dictionary comprehension is implemented in the above piece of code.


8. What will be the output of the following Python code?

 a={i: 'A' + str(i) for i in range(5)}

print(a)  

a) An exception is thrown

b) {0: ‘A0’, 1: ‘A1’, 2: ‘A2’, 3: ‘A3’, 4: ‘A4’}

c) {0: ‘A’, 1: ‘A’, 2: ‘A’, 3: ‘A’, 4: ‘A’}

d) {0: ‘0’, 1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’}


Answer: b 

Explanation: Dictionary comprehension and string concatenation is implemented in the above piece of code.


 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


Answer: a

Explanation: Variable x iterates over each letter in the string hence the length of each letter is 1.


No comments:

Post a Comment