Python 3.11+Annotations & typingconstruct
Starred expression in a subscript
syntax
a[*b] unpacks b into a tuple of indices: a[*b] is the same as a[tuple(b)]. Its main use is tuple[int, *Ts] in annotations (Python 3.11+).
Syntax
объект[*итерируемое]
объект[x, *итерируемое]
The main trap: __getitem__ always receives a tuple — even a[*[5]] passes (5,), not 5, so you cannot index a list this way: lst[*idx] raises TypeError. The construct is meant for multi-dimensional objects and generic types with TypeVarTuple, not for ordinary sequences. Before 3.11 the same code is a SyntaxError.
Examples
# Python 3.11+
class Show:
def __getitem__(self, key):
return key
s = Show()
idx = (1, 2)
print(s[*idx]) # → (1, 2)
print(s[0, *idx]) # → (0, 1, 2)
print(s[*[5]]) # → (5,)
# Python 3.11+
print(tuple[int, *tuple[str, ...]]) # → tuple[int, *tuple[str, ...]]
lst = [10, 20, 30]
idx = [1]
print(lst[*idx]) # → TypeError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy