Needless copying in iterations?

buffi bjorn.kempen at gmail.com
Sat Sep 15 18:17:02 EDT 2007


On Sep 16, 12:20 am, James Stroud <jstr... at mbi.ucla.edu> wrote:
> buffi wrote:
> > On Sep 15, 11:58 pm, James Stroud <jstr... at mbi.ucla.edu> wrote:
> >> Hello all,
>
> >> I was staring at a segment of code that looked like this today:
>
> >>     for something in stuff[x:y]:
> >>       whatever(something)
>
> >> and was wondering if the compiler really made a copy of the slice from
> >> stuff as the code seems to suggest, or does it find some way to produce
> >> an iterator without the need to make a copy (if stuff is a built-in
> >> sequence type)? Or would it be more efficient to do the more clumsy (in
> >> my opinion):
>
> >>     for i in xrange(x, y):
> >>       whatever(stuff[i])
>
> >> James
>
> > itertools.islice does what you want
>
> > import itertools
> > for something in itertools.islice(stuff, x, y):
> >       whatever(something)
>
> Thanks buffi!
>
> So I guess the interpreter does no optimization in the latter?
>
> James

No, as far as I know it makes a new list out of the slice when you do
it like
for something in stuff[x:y]

- Björn Kempén




More information about the Python-list mailing list