
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Iterator Types
In python there is iteration concepts over containers. Iterators have two distinct functions. Using these functions, we can use user defined classes to support iteration. These functions are __iter__() and the __next__().
Method __iter__()
The __iter__() method returns iterator object. If one class supports different types of iteration, then some other methods can be there to do some other tasks.
Method __next__()
The __next__() method returns the next element from the container. When the item is finished, it will raise the StopIteration exception.
Example Code
class PowerIter: #It will return x ^ x where x is in range 1 to max def __init__(self, max = 0): self.max = max #Set the max limit of the iterator def __iter__(self): self.term = 0 return self def __next__(self): if self.term <= self.max: element = self.term ** self.term self.term += 1 return element else: raise StopIteration #When it exceeds the max, return exception powIterObj = PowerIter(10) powIter = iter(powIterObj) for i in range(10): print(next(powIter))
Output
1 1 4 27 256 3125 46656 823543 16777216 387420489
- Related Articles
- Iterator function in Python
- Iterator Functions in Python
- Difference between Python iterable and iterator
- Flatten Nested List Iterator in Python
- Difference between Iterator and Spilt Iterator in Java.
- Iterator in Java
- Program to implement run length string decoding iterator class in Python
- Iterator Functions in C#
- Iterator Functions in Java
- Iterator Invalidation in C++
- RLE Iterator in C++
- Zigzag Iterator in C++
- Python Numeric Types
- Python Sequence Types
- Python Set Types

Advertisements