Given the following code, what is the final value of `result`?
```python
def modify(lst, val):
lst.append(val)
lst = [val]
return lst
nums = [1, 2]
result = modify(nums, 3)
result.append(4)
```
A. [3, 4]
B. [1, 2, 3]
C. [1, 2, 3, 4]
D. [3]
Correct Answer: A - [3, 4]
RATIONALE
Inside modify, lst.append(val) mutates the caller's list nums to [1,2,3],
but then lst is rebound to a new list [3]. The function returns this new
list. result refers to [3], and result.append(4) yields [3,4]. The original
nums is [1,2,3] but is not used.
Question 2
Which statement about Python's `range()` function is correct when used in a
`for` loop?
A. range(5, 0, -1) produces the sequence 5, 4, 3, 2, 1.
B. range(0, 5, -1) produces 0, -1, -2, -3, -4.
Page 2
, C. range(5) produces 1, 2, 3, 4, 5.
D. range(1, 5, 2) produces 1, 3, 5.
Correct Answer: A - range(5, 0, -1) produces the sequence 5, 4, 3,
2, 1.
RATIONALE
range(start, stop, step) generates values from start up to but excluding
stop. range(5,0,-1) yields 5,4,3,2,1. Option B is empty because step is
negative but start < stop. Option C starts at 0. Option D stops before 5,
yielding 1,3.
Question 3
What is the output of the following code?
```python
def outer():
x = 10
def inner():
nonlocal x
x += 5
return x
return inner()
print(outer())
```
A. 15
B. 10
C. UnboundLocalError
D. 5
Correct Answer: A - 15
Page 3
, RATIONALE
The nonlocal keyword allows inner to modify x in the enclosing scope
of outer. x starts at 10, becomes 15, and inner returns 15. Without
nonlocal, x += 5 would raise UnboundLocalError because x would be
treated as local to inner.
Question 4
Consider the dictionary `d = {'a': 1, 'b': 2, 'c': 3}`. After executing `d['a'] =
d.get('d', 0) + d.pop('b')`, what is the resulting dictionary?
A. {'a': 2, 'c': 3}
B. {'a': 3, 'c': 3}
C. {'a': 1, 'c': 3}
D. KeyError
Correct Answer: A - {'a': 2, 'c': 3}
RATIONALE
d.get('d', 0) returns 0 because 'd' is absent. d.pop('b') removes 'b' and
returns 2. The expression becomes d['a'] = 0 + 2 = 2. The final
dictionary is {'a': 2, 'c': 3}.
Question 5
Which of the following best describes the difference between a `list` and a
`tuple` in Python?
A. Lists are mutable and typically used for homogeneous sequences;
tuples are immutable and often used for heterogeneous records.
B. Lists can contain any data type; tuples can only contain numbers.
C. Tuples are mutable and support item assignment; lists are immutable.
D. Lists are indexed by integers; tuples are indexed by strings.
Correct Answer: A - Lists are mutable and typically used for
homogeneous sequences; tuples are immutable and often used for
heterogeneous records.
Page 4