...

/

Iterators and User-defined Iterators

Iterators and User-defined Iterators

Learn how to iterate over the iterables by using different techniques.

We'll cover the following...

Iterators

We know that we can iterate string and container objects like lists, tuples, sets, and dictionaries by using a for loop, as shown below:

Press + to interact
for ch in 'Good Afternoon' :
print(ch)
for num in [10, 20, 30, 40, 50] :
print(num)

In the code above, both of the for loops call the __iter__() method of the string and list. This method returns an iterator object. The iterator object has a method __next__(), which returns the next item in the string and list container.

When all items have been iterated, the next call to ...