Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an iterator to print integers

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

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()
like image 528
pandoragami Avatar asked Jan 14 '11 03:01

pandoragami


1 Answers

To access the values returned by an iterator, you use the next() method of the iterator like so:

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

next() has both the purpose of advancing the iterator and returning the next element. StopIteration is thrown when iteration is done.

Since this is quite cumbersome, all of this is wrapped nicely up in the for-syntax:

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

More links:

  • Python documentation on iterator.
like image 192
Sebastian Paaske Tørholm Avatar answered Nov 02 '22 23:11

Sebastian Paaske Tørholm