What will be the output of the following code: list_1 = [1]; list_2 = list_1; list_1[0] = 2; print(list_2)?

Study for the PCEP Certified Entry-Level Python Programmer Exam. Access multiple choice questions and detailed explanations to enhance your learning. Prepare effectively for your certification!

In the given code, list_1 is initially defined as a list containing a single element, which is 1. When list_2 is assigned to list_1, both variables now reference the same list object in memory. This means that any modifications made to list_1 will be reflected in list_2.

Next, the code updates the first element of list_1 to 2 with the assignment list_1[0] = 2. Since list_2 references the same list as list_1, it will also reflect this change. Therefore, when print(list_2) is called, it outputs the updated list, which is now [2].

This behavior demonstrates how mutable objects like lists in Python work, where multiple references to the same object can lead to changes being reflected across all references. Thus, the final output is [2].

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy