Iterator in python is any python type that can be used with a ‘for in loop’. Python lists, tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators because they implement following methods. In fact, any object that wants to be an iterator must implement following methods.
- __iter__ method that is called on initialization of an iterator. This should return an object that has a next or __next__ (in Python 3) method.
- next ( __next__ in Python 3) The iterator next method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.
How an iterator really works in python
G e e k s
Below is a simple Python custom iterator that creates iterator type that iterates from 10 to given limit. For example, if limit is 15, then it prints 10 11 12 13 14 15. And if limit is 5, then it prints nothing.
10 11 12 13 14 15
Examples of inbuilt iterator types.
List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345
This article is contributed by Shwetanshu Rohatgi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Infinite Iterators in Python
- Combinatoric Iterators in Python
- Python - Read blob object in python using wand library
- Python | Index of Non-Zero elements in Python list
- Reading Python File-Like Objects from C | Python
- Python | PRAW - Python Reddit API Wrapper
- Python | Convert list to Python array
- Python | Merge Python key values to list
- Important differences between Python 2.x and Python 3.x with examples
- MySQL-Connector-Python module in Python
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Sort Python Dictionaries by Key or Value
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Visualizing O(n) using Python
Improved By : Raisul