PCEP-30-02 · Question #58
Take a look at the snippet and choose the true statement: nums = [1, 2, 3] vals = nums del vals[:]
The correct answer is C. nums and vals have the same length. Option C is correct because vals = nums does not create a new list - it makes vals a second reference pointing to the exact same list object in memory. When del vals[:] is executed, it clears all elements from that shared list in-place, leaving both nums and vals as empty lists…
Question
Options
- Avals is longer than nums
- Bnums is longer than vals
- Cnums and vals have the same length
- DThe snippet will cause a runtime error.
How the community answered
(50 responses)- A4% (2)
- B16% (8)
- C72% (36)
- D8% (4)
Explanation
Option C is correct because vals = nums does not create a new list - it makes vals a second reference pointing to the exact same list object in memory. When del vals[:] is executed, it clears all elements from that shared list in-place, leaving both nums and vals as empty lists with length 0.
- A and B are wrong for the same reason: since there is only one list object, the two variables can never have different lengths - they are always identical.
- D is wrong because
del vals[:]is perfectly valid Python; slice deletion is a built-in operation that empties a list without raising any error.
Memory tip: In Python, = with a list copies the reference, not the data. Think of nums and vals as two name-tags stuck on one box - removing items from the box affects both tags. To get an independent copy, use vals = nums[:] or vals = nums.copy().
Community Discussion
No community discussion yet for this question.