How would you iterate a number backwards without using a list in Python 3?
Using lists, I would probably do something like:
li = list(range(100))
for i in li[::-1]:
print(i)
This is a fine solution, but it does not work with huge numbers.
Right now, I’m trying to iterate a number backwards with large numbers, but an overflow error happens, so I think I need to somehow find a way to iterate a number backwards without using lists.
Is there any way?
Iterators that provide the
__reversed__()special method also support reversed iteration. In Python 3.x,range()iterators have this method, so you can also useIn Python 2.x,
xarnge()allows reversed iteration:Both versions do not store the whole list in memory.