Solution: We are iterating over each letter in the string.
Q: Which of the following is the correct expansion of list_1 = [expr(i) for i in list_0 if func(i)]?
A. list_1 = []
for i in list_0:
if func(i):
list_1.append(i)
B. for i in list_0:
if func(i):
list_1.append(expr(i))
C. list_1 = []
for i in list_0:
if func(i):
list_1.append(expr(i))
D. none of the mentioned
Solution: We have to create an empty list, loop over the contents of the existing list and check if a condition is satisfied before performing some operation and adding it to the new list.
Q: What will be the output of the following Python code snippet?
x = [i**+1 for i in range(3)]; print(x);
A. [0, 1, 2]
B. [1, 2, 5]
C. error, **+ is not a valid operator
D. error, ‘;’ is not allowed
Solution: i**+1 is evaluated as (i)**(+1).
Q: What will be the output of the following Python code snippet?
print([i.lower() for i in "HELLO"])
A. [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
B. ‘hello’
C. [‘hello’]
D. hello
Solution: We are iterating over each letter in the string.
Q: What will be the output of the following Python code snippet?
print([i+j for i in "abc" for j in "def"])
A. [‘da’, ‘ea’, ‘fa’, ‘db’, ‘eb’, ‘fb’, ‘dc’, ‘ec’, ‘fc’]
B. [[‘ad’, ‘bd’, ‘cd’], [‘ae’, ‘be’, ‘ce’], [‘af’, ‘bf’, ‘cf’]]
C. [[‘da’, ‘db’, ‘dc’], [‘ea’, ‘eb’, ‘ec’], [‘fa’, ‘fb’, ‘fc’]]
D. [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’, ‘cf’]
Solution: If it were to be executed as a nested for loop, i would be the outer loop and j the inner loop.
Q: What will be the output of the following Python code snippet?
print([[i+j for i in "abc"] for j in "def"])
A. [‘da’, ‘ea’, ‘fa’, ‘db’, ‘eb’, ‘fb’, ‘dc’, ‘ec’, ‘fc’]
B. [[‘ad’, ‘bd’, ‘cd’], [‘ae’, ‘be’, ‘ce’], [‘af’, ‘bf’, ‘cf’]]
C. [[‘da’, ‘db’, ‘dc’], [‘ea’, ‘eb’, ‘ec’], [‘fa’, ‘fb’, ‘fc’]]
D. [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’, ‘cf’]
Solution: The inner list is generated once for each value of j.
Q: What will be the output of the following Python code snippet?
print([if i%2==0: i; else: i+1; for i in range(4)])
A. [0, 2, 2, 4]
B. [1, 1, 3, 3]
C. error
D. none of the mentioned
Solution: Syntax error.
Q: Which of the following is the same as list(map(lambda x: x**-1, [1, 2, 3]))?