I have seen in a lot of posts/materials saying xrange(num) is a generator/iterator. I have a couple of questions regarding that.
If xrange is an iterator/generator, it is supposed to have .next() method. I do not understand why the .next() method doesn't work for the case below.
def generator():
    for i in xrange(20): yield i
In the above example,
    numbers = generator()
    for i in numbers: 
        if i == 6: break
    for i in numbers:
        if i == 10: break
        print i
    >>> 7
    8
    9
    >>> print numbers.next()
    11 
The above functionalities also hold true for a object generator of the type:
    >>> numbers = (x for x in range(100))
If I do with xrange operation, the loop starts iterating from the beginning and there is no next() operation. I know that we can do the smart way of:
    for i in xrange(20):
        if (#something):
            var = i
            break
     #perform some operations
     for i in range(var,20):
         #Do something
But I want to loop to continue after var without using var.
To be short, is there a next() kind of operation for xrange. If yes : 'How?' , else : 'Why?'
xrange is an iterable, so you can call iter to get an iterator out of it.
>>> x = xrange(20)
>>> iterator = iter(x)
>>> for i in iterator:
...     if i == 6: break
...
>>> iterator.next()
7
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With