Using an iterator to print integers

What I want to do is print integers from 0 to 5 in the code below, but all I get is the iterator address?

def main():

    l = []
    for i in range(0,5):
        l.append(i)

    it = iter(l)

    for i in range(0,5):
        print it
        it.next()

if __name__ == '__main__':
    main()
+5
source share
3 answers

To access the values ​​returned by the iterator, you use the next () method of the iterator as follows:

try:
    while True:
        val = it.next()
        print(val)
except StopIteration:
    print("Iteration done.")

next () has the goal of promoting both an iterator and returning the next element. StopIteration is thrown when iteration is performed.

Since this is rather cumbersome, all of this is perfectly complemented by the syntax:

for i in it:
    print(i)
print("Iteration done.")

Other links:

+9

, , .

for i in it:
    print(i)
+3

When you use a for loop, you are actually calling the iterator object method __next__implicitly. This way you just won’t use something like a range, but instead just use an iterator.

for i in it:
    print i

What does it cost xrangein Python 2 and rangein Python 3 iterator returns, so you just write your first loop with those who have the desired solution,

+3
source

All Articles