nerdexam
Python_Institute

PCEP-30-02 · Question #23

What is the expected output of the following code? ``python 1 data = (1, ) * 3 2 data[0] = 2 3 print(data) ``

The correct answer is D. The code is erroneous. Option D is correct because tuples in Python are immutable - once created, their elements cannot be modified. Line 2 (data[0] = 2) attempts to reassign an element of the tuple, which raises a TypeError: 'tuple' object does not support item assignment at runtime, halting…

Question

What is the expected output of the following code?
1 data = (1, ) * 3
2 data[0] = 2
3 print(data)

Options

  • A(2, 1, 1)
  • B(1, 1, 1)
  • C(2, 2, 2)
  • DThe code is erroneous.

How the community answered

(22 responses)
  • A
    5% (1)
  • B
    5% (1)
  • C
    9% (2)
  • D
    82% (18)

Explanation

Option D is correct because tuples in Python are immutable - once created, their elements cannot be modified. Line 2 (data[0] = 2) attempts to reassign an element of the tuple, which raises a TypeError: 'tuple' object does not support item assignment at runtime, halting execution before print is ever reached.

  • A (2, 1, 1) is wrong because it assumes tuple assignment works like list assignment - it doesn't; tuples reject mutation entirely.
  • B (1, 1, 1) is wrong because it assumes the failed assignment is silently ignored and execution continues - Python raises an error instead.
  • C (2, 2, 2) is wrong on two counts: tuples are immutable, and even if they weren't, item assignment only targets the specified index, not all elements.

Memory tip: "Tuples are Tombstone data - set in stone, never changed." If you need a mutable sequence, use a list ([1] * 3); if you see a tuple on the left side of an assignment, expect an error.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice