Eric Hansen
Eric Hansen

Reputation: 1809

Why do lists have a __reverse__() special method but tuples don't in Python?

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?

Upvotes: 2

Views: 118

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124090

Tuples simply rarely are iterated over in reverse order.

That's because tuples are heterogenous, lists are homogenous; while lists have order, tuples are meant to have structure. As result, tuples are meant to be relatively small, while lists can be (very) large. See What's the difference between lists and tuples?

As such, there is simply no need to create a reverse iterator for tuples; it would be a premature optimisation, creating a maintenance cost for very little gain.

Upvotes: 4

Related Questions