Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration.
- __iter(iterable)__ method that is called for the initialization of an iterator. This returns an iterator object
- next ( __next__ in Python 3) The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object which further uses next() method to iterate over. This method raises 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 a given limit. For example, if the limit is 15, then it prints 10 11 12 13 14 15. And if the limit is 5, then it prints nothing.
10 11 12 13 14 15
In the following iterations, the for loop is internally(we can’t see it) using iterator object to traverse over the iterables
List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345
Generators in Python
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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Combinatoric Iterators in Python
- Infinite Iterators in Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Visualizing O(n) using Python
- Python | Index of Non-Zero elements in Python list
- Python | Convert list to Python array
- MySQL-Connector-Python module in Python
- Python - Read blob object in python using wand library
- Python | PRAW - Python Reddit API Wrapper
- twitter-text-python (ttp) module - Python
- Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
- Python program to check if the list contains three consecutive common numbers in Python
- Creating and updating PowerPoint Presentations in Python using python - pptx