Question 1
What will be the output of the following Python code snippet?
L = [10, 20, 30, 40, 50, 60, 70]
print(L[1:6:2])
Slicing L[start:stop:step] with start=1, stop=6, step=2 picks indices 1, 3, 5 which correspond to elements 20, 40, and 60.
What will be the output of the following Python code snippet?
L = [10, 20, 30, 40, 50, 60, 70]
print(L[1:6:2])
Slicing L[start:stop:step] with start=1, stop=6, step=2 picks indices 1, 3, 5 which correspond to elements 20, 40, and 60.
Consider the code below. What is the value of result after execution?
nums = [1, 2, 3]
result = nums * 2
result[0] = 99
print(nums)
The multiplication operator nums * 2 creates a brand new list. Modifying result[0] does not alter the original list nums.
What is the output of the following code involving list methods?
a = [1, 2, 3]
b = a.append(4)
print(a, b)
List method .append() mutates the list in-place and returns None. Therefore, a becomes [1, 2, 3, 4] and b is None.
What is the output of the following code using extend and append?
x = [1, 2]
y = [3, 4]
x.append(y)
z = [1, 2]
z.extend(y)
print(len(x), len(z))
x.append(y) adds the list y as a single element, making x = [1, 2, [3, 4]] (length 3). z.extend(y) iterates over y and appends each element individually, making z = [1, 2, 3, 4] (length 4).
What will be the output printed by the following Python code?
matrix = [[0]*3]*3
matrix[0][0] = 5
print(sum(matrix[1]))
[[0]*3]*3 creates 3 references to the SAME inner list [0, 0, 0]. Changing matrix[0][0] = 5 mutates the shared list to [5, 0, 0]. Thus matrix[1] is also [5, 0, 0], and its sum is 5.