Python Iterators

An iterator is an object that contains a countable number of values. In Python, an iterator is an object which implements the iterator protocol, consisting of the methods __iter__() and __next__().


Creating an Iterator

You can create an iterator from any iterable object, such as a list, tuple, or string, by using the iter() function.

Tutorials dojo strip

Explanation of Code:

In this example, my_list is an iterable, and my_iterator is an iterator created from my_list. The next() function is used to get the next item from the iterator.




Using Iterators in a Loop

Iterators are often used in loops to iterate through elements of a collection.

Explanation of Code:

You can use a for loop to automatically handle the iteration process. This loop will continue to print each item from the iterator until all items have been exhausted.




Creating a Custom Iterator

You can create a custom iterator by defining a class that implements the __iter__() and __next__() methods.

Explanation of Code:

In this example, MyNumbers is a custom iterator that returns numbers from 1 to 5. The __iter__() method initializes the iterator and the __next__() method returns the next value.




Python Iterators Example Code

Explanation of Code:

This program shows how to create an iterator from a list, use it in a loop, and create a custom iterator.




Python Labs

Tutorials dojo strip