[Python-ideas] Why don't CPython strings implement slicing using a view?
Andrew Barnert
abarnert at yahoo.com
Thu May 7 21:37:22 CEST 2015
On May 7, 2015, at 11:26, Terry Reedy <tjreedy at udel.edu> 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.
>
> it = iter(s)
> next(it)
> for c in it: process(c)
>
> for s[5555: 399999], use explicit indexes
>
> for i in range(5555, 400000): process s[i]
>
> or use islice.
>
> The use case for sequence views is when one needs to keep around both the base sequence and the slices (views).
Or where you need to keep around multiple views at once.
Since NumPy has native view-slicing, I suspect we can find a lot of good use cases there.
One question: when you slice a view, do you get a copy, or another view? Because if it's the latter, you can write view slices with view(s)[1:] instead of view(s, 1, None), which seems like a big readability win, but on the other hand it means a view doesn't act just like a normal sequence--e.g., v[:] no longer makes a copy. (NumPy does the latter, of course.)
> --
> Terry Jan Reedy
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
More information about the Python-ideas
mailing list