reversed(zip(...)) not working as intended
Tim Chase
python.list at tim.thechases.com
Sun Mar 6 13:51:53 EST 2016
On 2016-03-06 12:38, Tim Chase wrote:
> On 2016-03-06 19:29, Sven R. Kunze wrote:
> > what's the reason that reversed(zip(...)) raises as a TypeError?
>
> I'm not sure why reversed() doesn't think that the thing returned by
> zip() isn't a sequence.
Ah, a little more digging suggests that in 2.x, zip() returned a list
which "has a __reversed__() method [and] supports the sequence
protocol (the __len__() method and the __getitem__() method with
integer arguments starting at 0)."
In 3.x, zip() returns a generic iterator which neither has a
__reversed__() method nor has __len__() and __getitem__() methods.
So it looks like one needs to either
results = reversed(list(zip(...)))
or, more efficiently (doing it with one less duplication of the list)
results = list(zip(...))
results.reverse()
-tkc
More information about the Python-list
mailing list