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.

So I tried my handle at a little class called xslice (the x from xrange to 
indicate its a generator (although I'm not sure if that's technically correct)).

With it, instead of the above example you can do:


seq = range(10)
for even in xslice(seq, 0, len(seq), 2):
    print even


It would be more or less like using xrange. I know the syntax is not that much 
of an improvement over just using exrange and retrieving items by index, but 
it's the concept I'm looking at.

Do you think this or something like be a builtin in the future?
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to