Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #104165
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: reversed(zip(...)) not working as intended |
| Date | 2016-03-06 19:53 +0100 |
| Organization | None |
| Message-ID | <mailman.263.1457290429.20602.python-list@python.org> (permalink) |
| References | <56DC7727.1090001@mail.de> |
Sven R. Kunze wrote:
> what's the reason that reversed(zip(...)) raises as a TypeError?
>
> Would allowing reversed to handle zip and related functions lead to
> strange errors?
In Python 3 zip() can deal with infinite iterables -- what would you expect
from
reversed(zip(count()))
?
If all arguments of zip() are finite and of equal length you can write
zip(reversed(a1), reversed(a2), ...)
or if you find that really useful something like
>>> class myzip(zip):
... def __init__(self, *args):
... self.args = args
... def __reversed__(self):
... return zip(*(reversed(a) for a in self.args))
...
>>> list(reversed(myzip("abc", [1,2,3])))
[('c', 3), ('b', 2), ('a', 1)]
While this might look right at first sight it really opens a can of worms.
First zip():
>>> z = zip("abc", "def")
>>> next(z)
('a', 'd')
>>> list(z)
[('b', 'e'), ('c', 'f')]
Now myzip():
>>> m = myzip("abc", "def")
>>> next(m)
('a', 'd')
>>> list(reversed(m))
[('c', 'f'), ('b', 'e'), ('a', 'd')]
Frankly, I have no idea what consistent behaviour should look like for a
zip() that can be "reverse-iterated".
PS: In Python 2 zip() would produce a list, so
>>> list(reversed(zip("abc", "def")))
[('c', 'f'), ('b', 'e'), ('a', 'd')]
worked without requiring any code in zip().
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: reversed(zip(...)) not working as intended Peter Otten <__peter__@web.de> - 2016-03-06 19:53 +0100
csiph-web