3 ms·
I was intrigued to see how this worked out in practice for Python 3, where range returns an iterator rather than a list— like, would reversing the iteration req
by mikepurvis 7y ago
I was intrigued to see how this worked out in practice for Python 3, where range returns an iterator rather than a list— like, would reversing the iteration require allocating the whole list in memory?
$ python3 -c 'print(reversed(range(10)))'
<range_iterator object at 0x7fdb53ae96f0>
It turns out that reversed() only works on objects that expose the __len__ and __getitem__ methods:
https://www.python.org/dev/peps/pep-0322/ https://www.python.org/dev/peps/pep-0322/
If you try to use reversed() with your own generator it will fail with "TypeError: argument to reversed() must be a sequence", until you wrap the generator invocation in an explicit list().
Very nice.