
- 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
Iterator function in Python
Explanation
Iterator is an object in python that implements iteration protocol. Tuples,lists,sets are called inbuilt iterators in Python.There are two types of method in iteration protocol.
__iter__() : This method is called when we initialize an iterator and this must return an object which consist next() or __next__()(in Python 3) method.
next() or __next__() (in Python 3) : This method should returns the next element from a iteration sequence.When an iterator is used with a for loop the for loop directly call the next() on the iterator object.
Example Code
# creating a custom iterator class Pow_of_Two: def __init__(self, max = 0): self.max = max def __iter__(self): self.n = 0 return self def __next__(self): if self.n <= self.max: result = 2 ** self.n self.n += 1 return result else: raise StopIteration("Message") a = Pow_of_Two(4) i = iter(a) print(i.__next__()) print(next(i)) print(next(i)) print(next(i)) print(next(i)) print(next(i))
Output
1 2 4 8 16 StopIteration error will be raised
- Related Articles
- Iterator Functions in Python
- Python Iterator Types
- Flatten Nested List Iterator in Python
- Difference between Python iterable and iterator
- Difference between Iterator and Spilt Iterator in Java.
- Iterator in Java
- How to get index in a sorted array based on iterator function in JavaScript?
- Iterator Functions in Java
- RLE Iterator in C++
- Zigzag Iterator in C++
- Iterator Functions in C#
- Iterator Invalidation in C++
- Program to implement run length string decoding iterator class in Python
- DoubleStream iterator() method in Java
- IntStream iterator() method in Java

Advertisements