GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||
GeezerVison is showing www.geeksforgeeks.org — Iterators in Python - GeeksforGeeks Iterators in PythonLast Updated : 5 Jun, 2026 An iterator in Python is an object used to traverse through all the elements of a collection (like lists, tuples or dictionaries) one element at a time. It follows the iterator protocol, which involves two key methods:
Need For IteratorsHere are some key benefits:
Built-in IteratorPython provides built-in iterators for iterable objects such as strings, lists, tuples, and dictionaries. These iterators allow elements to be accessed one at a time using the next() function. Example: Let’s start with a simple example using a string. We will convert it into an iterator and fetch characters one by one:
Output G F G Explanation:
Creating a Custom IteratorCreating a custom iterator in Python involves defining a class that implements the __iter__() and __next__() methods according to the Python iterator protocol. Steps to follow:
Below is an example of a custom class called EvenNumbers, which iterates through even numbers starting from 2:
Output 2 4 6 8 10 Explanation:
StopIteration ExceptionStopIteration exception is integrated with Python’s iterator protocol. It signals that the iterator has no more items to return. Once this exception is raised, further calls to next() on the same iterator will continue raising StopIteration. Example:
Output 100 200 300 End of iteration In this example, the StopIteration exception is manually handled in the while loop, allowing for custom handling when the iterator is exhausted. Iterator vs IterableAlthough the terms iterator and iterable sound similar, they are not the same. An iterable is any object that can return an iterator, while an iterator is the actual object that performs iteration one element at a time. Example: Let’s take a list (iterable) and create an iterator from it
Output 1 2 3 Explanation:
To make the difference even clearer, let’s summarize it in a simple table:
Comment Explore | |||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |