xslice idea | a generator slice

Ian Kelly ian.g.kelly at gmail.com
Thu Jul 11 18:16:38 CEST 2013


On Thu, Jul 11, 2013 at 8:52 AM, Russel Walker <russ.pobox at gmail.com> wrote:
> Just some dribble, nothing major.
>
> I like using slices but I also noticed that a slice expression returns a new sequence.
>
> I sometimes find myself using them in a for loop like this:
>
>
> seq = range(10)
> for even in seq[::2]:
>     print even
>
>
> (That's just for an example) But wouldn't it be a bit of a waste if the slice expression returns a whole new list just when all you want to do in this case is iterate over it once?
>
> I suppose you could get around that will a little more code like:
>
>
> seq = range(10)
> for x in xrange(0, len(seq), 2):
>     print seq[x]
>
>
> But it would be nice there was a way to iterate over a 'slice' of sorts, that would act as a generator.

That would be the itertools.islice function.



More information about the Python-list mailing list