Tuple Item Assignment

ID

python.tuple_item_assignment

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Python

Tags

reliability, suspicious-construct

Description

Reports assignments to a subscript of a tuple literal — (1, 2, 3)[0] = 9 or tuple([1])[0] = 9. Tuples are immutable; the runtime raises TypeError: 'tuple' object does not support item assignment on the first execution. The rule is conservative: it fires only on syntactically obvious tuple subscripts (literal tuples or tuple(…​) calls).

(1, 2, 3)[0] = 9              # FLAW
tuple([1, 2])[0] = 9          # FLAW

[1, 2, 3][0] = 9              # OK — list subscript assignment

Rationale

The pattern almost always means the developer meant a list, or meant to construct a new tuple with the change. Either way, the runtime will fail; static detection avoids the production crash.

A more comprehensive rule would track the type of the subscripted expression and flag any assignment to a tuple-typed variable. That requires type inference; the current rule is the syntactic subset that does not.

Remediation

Use a list if the data is meant to be mutable:

items = [1, 2, 3]
items[0] = 9

Or rebuild the tuple immutably:

old = (1, 2, 3)
new = (9, *old[1:])

References