3 ms·
In Python, reversed(range(0, n)) (which is also a thing you can write—does that help?) is indeed written range(n-1, -1, -1), but I think I recently encountered
by mananaysiempre 4y ago
In Python, reversed(range(0, n)) (which is also a thing you can write—does that help?) is indeed written range(n-1, -1, -1), but I think I recently encountered a language where that was written as (the local syntax’s equivalent of) range(n, 0, -1), that is to say the rule was not “start inclusive, end exclusive” but “low inclusive, high exclusive”. I’m not sure what language it was and whether this option ultimately ends up more intuitive, but in any case it’s a valid option.
(One difference is that the start-end rule can work polymorphically with equality only, while the low-high rule requires an ordering.)
- chkas 4y agoWith Knuth-Shuffle, it would be: for i in reversed(range(1, len(x))): That makes it better, but not much.
- formerly_proven 4y agoA potential issue with reversed(range(...)) is reversed() eagerly constructing the entire range.
- mananaysiempre 4y agoNope: unlike, say, sorted(), reversed() will never force an iterator into a sequence—it will either call __reversed__ or fall back to __len__ and __getitem__. An iterator needs to know how to reverse itself, or it’s out of luck. (Which is quite annoying because it forces you to write a class rather than a generator function.) Ranges are in the former category, they know how to reverse themselves[1]. (Yet for some reason range(0, 42) and range(41, -1, -1) repr themselves as range(0, 42) and range(41, -1, -1) respectively while reversed(range(0, 42)) is instead <range_iterator object at ...>. Truly, I cannot touch anything without finding a bug or at least a suspiciously insectoid lifeform.) [1] https://github.com/python/cpython/blob/7e3f09cad9b783d8968aa79ff6a8ee57beb8b83e/Objects/rangeobject.c#L1115 https://github.com/python/cpython/blob/7e3f09cad9b783d8968aa...
- formerly_proven 4y agoThanks, TIL about the __reversed__ protocol despite having lived in chapter three of the Python reference for some time.