slicing return iter?

StarWing weasley_wx at
Sat Oct 17 16:40:47 CEST 2009

hello everyone, I'm new here :-)

sometimes I want to iterate a part of a sequence. but don't want to
copy it. i.e.

a = list(...)
# now a is a list, and a[:] is another list, and so a[m:n]
# now we do something with the 0~len(a)-3 elements of a
for val in a[:-2]:
    #do something....

but, this will cause a copy on a, has some convenience way to get a
iter to iterate on a part of list?

i made this:
class iterslice:
    def __init__(self, list):
        self.list = list

    def __len__(self):
        return len(self.list)

    def __getitem__(self, slice):
        import itertools
        listlen = len(self.list)
        range = (((slice.start + listlen) % listlen) if slice.start
else 0,
                ((slice.stop + listlen) % listlen) if slice.stop else
        return itertools.islice(self.list, *range)

a = [1,2,3,4]
for i in iterslice(a)[:-1:2]:
    print i

my question is:
  - are there any *Standard* way to do this? (a buit-in function? a
  - are there any better implements?

thanks for attention :-)

More information about the Python-list mailing list