Search code examples
pythonrangeyieldxrange

Python best practices xrange yield


def list_step(max = 268):    
    """ split in steps of 120 elements at time
    """
    if max > 120:
        for i in xrange(0,max,120):
            if i <= max:
                rest =  max % xrange(0,max,120)[-1]
                if rest != 120:
                    yield(i, rest)
                else:
                    yield(i, 0)
    else:
        yield(max)


a = list_step()
a.next()      return > (0,28) (120,28),ecc

Would it be possible to return the rest on the execution of last next(), instead of the tuple with the rest?

so that :

    a.next()      return > (0) (120),ecc.. (28)

Solution

  • something like this ?

    def list_step(max = 268):    
        """ split in steps of 120 elements at time
        """
        if max > 120:
            rest_list = [];
            for i in xrange(0,max,120):
                if i <= max:
                    rest =  max % xrange(0,max,120)[-1]
                    if rest != 120:
                        yield(i)
                        rest_list.append(rest)
                    else:
                        yield(i)
                        rest_list.append(0)
            for i in rest_list:
                yield(i)
        else:
            yield(max)
    
    
    a = list_step()
    for i in a: print i;