The reversed(seq)
built-in in Python indicates that seq
must have a __reversed__()
method or support the sequence protocol. Lists and tuples both obviously support the sequence protocol, but lists have their own __reversed__()
method used instead.
>>> hasattr(list, '__reversed__')
True
>>> hasattr(tuple, '__reversed__')
False
Then there must be some faster optimization in __reverse__()
for a list than the sequence protocol would provide for reversing. So I took a look at the source code where __reversed__()
is implemented for listobject.c, and with my pitifully limited C knowledge I cannot understand why a tuple (tupleobject.c) wouldn't have similar internal reversing methods, as a tuple appears to me to bean array with some optimizations (PyTuple_MAXSAVESIZE
) on allocations and memory, and a list to be a more familiar array.
What is the C magic I am missing that makes implementing a __reversed__()
method an optimization for the list type, but the standard iterator protocol better for tuples?