Discover the surprising behavior of Python lists when assigning one list to another variable and deleting slices. Learn how list references and lengths are affected in this PCEP-30-02 certification exam question.
Table of Contents
Question
Take a look at the snippet, and choose the true statements: (Choose two.)
nums = [1, 2, 3] val = nums del vals[1:2]
A. nums is longer than vals
B. nums and vals are of the same length
C. vals is longer than nums
D. nums and vals refer to the same list
Answer
B. nums and vals are of the same length
D. nums and vals refer to the same list
Explanation
When you assign one list to another variable in Python, both variables refer to the same list object in memory. So after the line `val = nums`, `val` and `nums` are two different names pointing to the same underlying list `[1, 2, 3]`.
The `del` statement is used to remove slices from a list. The syntax `del vals[1:2]` removes a slice containing just the element at index 1 from `vals`. So this removes the element `2` from the list.
However, since `vals` and `nums` refer to the same list, the deletion affects the list referenced by both variables. After the `del` statement, the underlying list is `[1, 3]`.
Therefore, the correct statements are:
B. nums and vals are of the same length
D. nums and vals refer to the same list
Both `nums` and `vals` still point to the same list object, which after the deletion contains `[1, 3]`. The list has length 2, so `nums` and `vals` have the same length.
Python Institute PCEP-30-02 certification exam practice question and answer (Q&A) dump with detail explanation and reference available free, helpful to pass the Python Institute PCEP-30-02 exam and earn Python Institute PCEP-30-02 certification.