Skip to content

Iterators

Iterators provide a way to access elements of a collection sequentially without exposing the underlying structure

numbers = [1, 2, 3, 4, 5, 6]
iterator = iter(numbers)  # Lazy loading of the list
iterator

print(next(iterator))
print(next(iterator))

1

2

1
2
3
4
5
6
7
numbers = [1, 2, 3, 4, 5, 6]
iterator = iter(numbers)
try:
    while True:
        print(next(iterator))
except StopIteration:
    print("Reached the end of the iterator.")

1

2

3

4

5

6

Reached the end of the iterator.