Python Programming
Python fundamentals to advanced for interviews
Showing 21–25 of 25 questions
Consider the following code:
x = [1, 2, 3]
y = x[::-1]
print(y)
What will be the output?
x = [1, 2, 3]
y = x[::-1]
print(y)
What will be the output?
Correct Answer:
B. [3, 2, 1]
EXPLANATION
The slice notation [::-1] reverses the list. [1, 2, 3] reversed is [3, 2, 1].
Which of the following will raise an IndexError?
Correct Answer:
B. lst = [1, 2, 3]; lst[3]
EXPLANATION
A list with 3 elements has valid indices 0, 1, 2. Index 3 is out of range and raises IndexError.
What will be the output of:
x = [1, 2, 3]
y = x
x.append(4)
print(y)
x = [1, 2, 3]
y = x
x.append(4)
print(y)
Correct Answer:
B. [1, 2, 3, 4]
EXPLANATION
y = x creates a reference to the same list, not a copy. When x is modified, y reflects the changes.
What is the output of: print(2 ** 3 ** 2)?
Correct Answer:
A. 512
EXPLANATION
The operator is right-associative. So 2 3 2 = 2 (3 2) = 2 9 = 512.
What will be the output of the following code?
x = [1, 2, 3]
x.append([4, 5])
print(len(x))
x = [1, 2, 3]
x.append([4, 5])
print(len(x))
Correct Answer:
B. 4
EXPLANATION
append() adds the entire list [4, 5] as a single element. So x becomes [1, 2, 3, [4, 5]] with length 4.