How to start a loop with a specific iterator
Question: I want to loop through a list in several loops always starting with the item
of the last loop:

    
    
    import itertools as it
    list1=[1,2,3,4,5,6,7,8]
    a=iter(list1)
    while a.next()!= 8:
        a,b=it.tee(a) #copy the iterator
        while b.next()!=8:
            b,c=it.tee(b)
            while c.next()!=8:
                print "yaaay"
    

in this code I can start my loop with the current iterator of the outer loop.
How to do this in a more pythonic way not using slice?

here is an example of what I'm thinking of a more pythonic way:

    
    
    list1=[1,2,3,4,5,6,7,8]
    a=iter(list1)
    for k1 in list1:
        for k2=k1 in list1:
            for k3=k2 in list1:
                print "yaaay"            
    


Answer: From my understanding, you're looking for the way to "save" the generator
state at some point and then "restore" it. Using `tee` is the correct idea,
[PEP 0323](http://www.python.org/dev/peps/pep-0323/) has more info on this.

    
    
    import itertools
    
    lst = range(10)
    it = iter(lst)
    
    while True:
        print it.next(), '>>',
        it, saved = itertools.tee(it)
        for subitem in it:
            print subitem,
        it = saved
        print
    

Update:

    
    
    import itertools
    
    class fancy_it(object):
        stack = []
    
        def __init__(self, iterable=None):
            if not iterable:
                prev = fancy_it.stack[-1]
                prev.it, iterable = itertools.tee(prev.it)
            self.it = iter(iterable)
    
        def __iter__(self):
            fancy_it.stack.append(self)
            try:
                while True:
                    yield self.it.next()
            except StopIteration:
                fancy_it.stack.pop()
                raise StopIteration
    
    
    for x in fancy_it(range(10)):
        print x
        for y in fancy_it():
            print '**', y
            for z in fancy_it():
                print '****', z
    

