PCEP-30-02 practice question 32 of 35

What is the output of the following Python code? my_tuple = (1, 2, 3) my_tuple[2] = 4 print(my_tuple)

Full set: 548 questions

Domain Data Collections – Tuples, Dictionaries, Lists, and Strings

Answer options
A: [1, 2, 3]
B: (1, 2, 3)
C: Error: 'tuple' object does not support item assignment Correct answer
D: (1, 2, 4)
Correct Answer:
C. Error: 'tuple' object does not support item assignment
Explanation

The code initializes a tuple named mytuple. Tuples are an immutable data type in Python, meaning their elements cannot be changed after the tuple is created. The line mytuple[2] = 4 attempts to perform an item assignment, modifying the element at index 2. Because tuples are immutable, this operation is illegal and raises a TypeError. The program execution halts at this line, and the print() function is never called. The resulting error message is specifically "'tuple' object does not support item assignment".

Why Incorrect

A. [1, 2, 3] is incorrect because the output would be a list, not a tuple, and the code raises an error before any output is produced.
B. (1, 2, 3) is incorrect because the program terminates with an error and does not reach the print statement.
D. (1, 2, 4) is incorrect because this would only be possible if tuples were mutable, which they are not.

References

1. Python Software Foundation. (2024). The Python Tutorial, Section 5.3: Tuples and Sequences. The official documentation states, "Tuples are immutable... It is not possible to assign to the individual items of a tuple...". It provides an example that trying to do so, e.g., t[0] = 88888, results in a TypeError.

Source: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences

2. Guttag, J. V. (2016). Introduction to Computation and Programming Using Python, With Application to Understanding Data (2nd ed.). MIT Press. In Chapter 5, which covers structured types, the text clarifies the distinction between lists and tuples: "Tuples are immutable... In contrast, lists are mutable." (Section 5.3, p. 79). This fundamental concept explains why the assignment fails.

3. Python Institute. (2024). PCEP-30-02 Exam Syllabus. Section 2.3, "Collections: Lists, Tuples, and Dictionaries," explicitly lists "mutability and immutability of tuples" as a key objective, confirming that understanding this behavior is essential for the exam.

Scroll to Top