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()
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:
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