python / cpython

The Python programming language
https://www.python.org
Other
63.18k stars 30.25k forks source link

Allow zip to be reversible if inputted iterables are reversible #112627

Closed Gobot1234 closed 10 months ago

Gobot1234 commented 10 months ago

Feature or enhancement

Proposal:

>>> reversed(zip((1, 2), (3, 4)))
TypeError: 'zip' object is not reversible

But individually

>>> zip(reversed((1, 2)), reversed((3, 4)))
<zip ((2, 4), (1, 3))>

works

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

terryjreedy commented 10 months ago

Python iterators are forward iterators and are generally not reversible unless one run them to exhaustion while collecting the items in a list and reversing the list. list(reversed(list(zip((1,2), (3,4))))) == [(2, 4), (1, 3)]. A zip, as an iterator, is nothing special in this regard. So the request does not make much sense.

If an iterator is, in a particular case, based on one or more reversible iterables, then in some cases one might in effect reverse the iterator by reversing the iterables, as you did. Builtins map and filter and some of the itertools iterators can also be reversed this way. But what is special about iterators based on multiple iterables, like zip, is the need for all input iterables to yield the same number of items for reversing them to give the expected result. And there is no way to determine equal length without running the underlying iterables.

I think that this issue should be closed.

gvanrossum commented 10 months ago

This is a minor feature, which does not need previous discussion elsewhere

I disagree -- unless this was already discussed and refined on discuss.python.org (in the Ideas topic) this does not have much of a chance of getting added.