Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a range_iterator when a range is reversed?

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?

like image 638
cat Avatar asked Mar 07 '16 00:03

cat


2 Answers

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).

like image 99
Blckknght Avatar answered Oct 19 '22 23:10

Blckknght


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]

Edit

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
like image 31
AMACB Avatar answered Oct 20 '22 00:10

AMACB