Suppose a Python tuple TUP is declared as TUP=('A','B','C') Which of the…

2023

Suppose a Python tuple TUP is declared as TUP=('A','B','C') Which of the following command is invalid ?

  1. A.

    TUP=('D')

  2. B.

    TUP=('D',)

  3. C.

    TUP+=('D')

  4. D.

    TUP+=('D',)

Attempted by 1581 students.

Show answer & explanation

Correct answer: C

Answer: The invalid command is TUP+=('D').

Reason: ('D') is not a tuple but the string 'D'. Trying to concatenate a tuple and a string with += raises a TypeError: can only concatenate tuple (not "str") to tuple.

  • TUP=('D') — valid Python, but this assigns the string 'D' (not a tuple). Use a trailing comma to make a one-element tuple.

  • TUP=('D',) — valid: this is a one-element tuple containing 'D'.

  • TUP+=('D') — invalid: ('D') is a string, so tuple + string raises a TypeError.

  • TUP+=('D',) — valid: concatenates two tuples. Although tuples are immutable, += will rebind the name TUP to the new tuple result.

Tip: when creating a single-element tuple, always include the trailing comma: ('element',).

Explore the full course: Rssb Senior Computer Instructor