[Python-ideas] What are the strong use cases for str.rindex()?

Steven D'Aprano steve at pearwood.info
Fri Apr 26 00:56:08 EDT 2019

On Fri, Apr 26, 2019 at 12:17:57AM -0400, Terry Reedy wrote:
> On 4/25/2019 7:12 PM, Greg Ewing wrote:
> >Steven D'Aprano wrote:
> >>I too often forget that reverse() returns an iterator,
> I presume you mean reversed().  list.reverse() is a list

Yes, I meant reversed(), not list.reverse() which is an in-place mutator 
method and returns None.

> >That seems like a mistake. Shouldn't it return a view?
> RL = reversed(somelist) is already partly view-like.  The nth next call 
> returns the nth item at the time of the next call, rather than at the 
> time of the reversed call.  However, the number of items produced by 
> next calls is the length of the list at the time of the reversed call. 

That's not quite correct:

py> L = [1, 2, 3]
py> R = reversed(L)
py> L.clear()
py> next(R)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

It seems that:

- in-place modifications in the list are reflected in the items
  yielded (so reversed() doesn't make a copy of the list);

- operations which extend the length of the list don't show up 
  in the reversed version;

- and operations which decrease the length of the list decrease
  the number of items yielded.

That suggests to me an implementation similar to:

# untested
def reversed(alist):
    N = len(alist)
    for i in range(N-1, -1, -1):
            yield alist[i]
        except IndexError:
    raise StopIteration

which I suppose is close to what you meant here:

> The first next(RL) is the current somelist[captured_length].


More information about the Python-ideas mailing list