Tuple slices

George Sakkis gsakkis at rutgers.edu
Wed Jan 26 10:39:26 EST 2005


"Bengt Richter" <bokr at oz.net> wrote in message news:41f772b2.1858112584 at news.oz.net...
> On Wed, 26 Jan 2005 11:55:59 -0800, jfj <jfj at freemail.gr> wrote:
>
> >Jeff Shannon wrote:
> >
> >>
> >>
> >> So, what problem is it, exactly, that you think you'd solve by making
> >> tuple slices a view rather than a copy?
> >>
> >
> >I think views are good for
> >  1) saving memory
> >  2) saving time (as you don't have to copy the elements into the new tuple)
> >
> >And they are worth it. However, (as in other cases with slicing), it is
> >very easy and fast to create a view for a slice with the default step
> >'1', while it's a PITA and totally not worth it to create a view for a
> >slice with non default step. I think it would be good to:
> >
> >  if slice_step == 1
> >    create_view
> >  else
> >    create_new_tuple
> >
> >Actually, i think that slices with step, is a bad feature in general
> >and i think I will write a PEP to suggest their removal in python3k.
> >
> What's the big deal with other than 1 steps? It is just adjusting a few numbers
> so that you can either index the new virtual slice with an integer and return the
> element, in which case the index into the original tuple will be
> someoffset+i*somefactor once you get past the limit checks for the virtual
> slice. By the same token, transforming a few numbers of one virtual slice
> into similar numbers for a a new virtual slice of that shouldn't be rocket science.
> And it wouldn't have to be done more than once.  Don't have time to do it now,
> but there are plenty around here that could, I'm sure.
>
> Regards,
> Bengt Richter

Here's my (undocumented) version of it: http://rafb.net/paste/results/HkxmHp37.html
and its unit test: http://rafb.net/paste/results/2LIInT68.html

And some useless timing comparisons (I know it's a stupid example, don't flame me for this):

$ python /usr/lib/python2.3/timeit.py \
    -s "x=tuple(xrange(10000))" \
    "[x[1:-1] for n in xrange(100)]"
10 loops, best of 3: 3.84e+04 usec per loop

$ python /usr/lib/python2.3/timeit.py \
    -s "from immutableseq import ImmutableSequence" \
    -s "x=ImmutableSequence(xrange(10000))" \
    "[x[1:-1] for n in xrange(100)]"
100 loops, best of 3: 5.85e+03 usec per loop

Feel free to comment or suggest improvements.

George






More information about the Python-list mailing list