I can subscript a range
object:
>>> r = range(4)
>>> r
range(0, 4)
>>> r[3]
3
>>> for i in r:
print(i)
0
1
2
3
>>> list(r)
[0, 1, 2, 3]
But, if I call reversed
on the same range
object:
>>> r = reversed(range(4))
>>> r
<range_iterator object at memaddr>
>>> for i in r:
print(i)
3
2
1
0
>>> r[3]
TypeError: 'range_iterator' object is not subscriptable # ?
>>> range(r)
TypeError: 'range_iterator' cannot be interpreted as an integer # ?
>>> list(r)
[] # ? uhmm
Hmm... Acting kinda like a generator but less useful.
Is there a reason a reversed range object isn't like a normal generator / iterator in how it quacks?
The reversed
function returns an iterator, not a sequence. That's just how it's designed. The range_iterator
you're seeing is essentially iter
called on the reversed range
you seem to want.
To get the reversed sequence rather than a reverse iterator, use the "alien smiley" slice: r[::-1]
(where r
is the value you got from range
). This works both in Python 2 (where range
returns a list) and in Python 3 (where range
returns a sequence-like range
object).
You need to change r
back to a list
type. For example:
reversed([1,2]) #prints <listreverseiterator object at 0x10a0039d0>
list(reversed([1,2])) #prints [2,1]
To clarify what you are asking, here is some sample I/O:
>>> r = range(5)
>>> x = reversed(r)
>>> print x
<listreverseiterator object at 0x10b6cea90>
>>> x[2]
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
x[2]
TypeError: 'listreverseiterator' object has no attribute '__getitem__'
>>> x = list(x)
>>> x[2] #it works here
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With