[Python-ideas] Why don't CPython strings implement slicing using a view?

Steven D'Aprano steve at pearwood.info
Fri May 8 04:11:26 CEST 2015


On Thu, May 07, 2015 at 02:26:06PM -0400, Terry Reedy wrote:
> On 5/7/2015 11:46 AM, Steven D'Aprano wrote:
> >On Wed, May 06, 2015 at 07:05:15PM -0700, Neil Girdhar wrote:
> >>Since strings are constant, wouldn't it be much faster to implement string
> >>slices as a view of other strings?
> >
> >String or list views would be *very* useful in situations like this:
> >
> ># Create a massive string
> >s = "some string"*1000000
> >for c in s[1:]:
> >     process(c)
> 
> Easily done without slicing, as discussed on python-list multiple times.

For some definition of "easy".

If all you want is to skip the first item, this is not too bad:

> it = iter(s)
> next(it)
> for c in it: process(c)

Skipping the *last* item, on the other hand?

for c in s[:-1]:
    process(c)

Yes, it can be done, but its even messier and uglier and a sequence view 
would make it neat and pretty:

it = iter(s)
prev = next(it)
for c in it:
    process(prev)
    prev = c


> for s[5555: 399999], use explicit indexes
> for i in range(5555, 400000): process s[i]

What, are we programming in Fortran, like some sort of Neanderthal?

*grins*


The point isn't that we cannot solve these problems without views, but 
that views would let us solve them in a clean Pythonic manner.



-- 
Steve


More information about the Python-ideas mailing list