Python Tuple Question | Output MCQ | daily coding challenge | Day 10

  What Is the Output of This python Code?

Python coding challenge day -10


Question :

x = (1, 2, 3)

x[0] = 5

print(x)


Options :

A) (5, 2, 3)

B) (1, 2, 3)

C) TypeError

D) Error


Correct answer :

C) TypeError


Exaplanation :

Step 1 - Creating a tuple

x = (1, 2, 3)

Here x is tuple containing three elements.

(1, 2, 3)

Index postions :

Index :   0   1   2

Value :   1   2   3


Step 2 - Trying to change a value

x[0] = 5

This line tries to change the value at index 0.

Python attempts to convert:

(1, 2, 3)

into 

(5, 2, 3)


Step 3 - Understanding Tuples

Tuples in python are immutable.

Immutable Means :

  • Values cannot be changed
  • Items cannot be added
  • Items cannot be removed

So Python does not allow modifying tuple elements.


Step 4 - Python Raises an error

Because tuples cannot be modified python raises an error:

TypeError: 'tuple' object does not support item assignment


Final output :

TypeError


Key points :

  • Lists are mutable (can be changed )
  • Tuples are immutable (cannot be changed )
  • Attempting to modify a tuple causes Type Error
  • Tuples use ( ) Parentheses


Example :

list → [1,2,3]  ✓ change allowed

tuple → (1,2,3) ✗ change not allowed


Practice daily python coding challenges to improve your programming and logical thinking skills.

Happy coding ❤️






No comments:

Post a Comment