List vs Tuple Mutability

Easy ⏱ 8 min 80% acceptance ★★★★★ 4.6
Write a function try_mutate(container, index, new_value) that attempts to set container[index] = new_value. If container is mutable (e.g. a list), perform the mutation and return the modified container. If it is immutable (e.g. a tuple) and the assignment raises TypeError, return the string "immutable" instead.

Examples

Example 1
Input
try_mutate([1, 2, 3], 0, 99)
Output
[99, 2, 3]
Explanation

Lists support item assignment.

Example 2
Input
try_mutate((1, 2, 3), 0, 99)
Output
'immutable'
Explanation

Tuples raise TypeError on item assignment.

Constraints

  • `container` is a list or a tuple.
  • Do not use isinstance — rely on the actual assignment failing.

Topics

Variables & Data Typesmutability

Companies

GoogleAdobe

Hints

Hint 1

Use try/except TypeError around the assignment.

Hint 2

Return container after mutating, inside the try block.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.