Course Content
What is Python?
Introduction of Python and Its setup
0/2
Control Statement
Control statements are used to control the flow of execution depending upon the specified condition/logic.
0/4
File Handling
File handling is an important component of any application. Python has multiple functions for creating, reading, updating, and deleting files.
0/2
Examples
Following are the examples of python scripts to try hands-on, you are ready to start your python journey.
0/7
Python
About Lesson

What is Iterators in Python?

An integrator is an object that can be iterated upon which means that you can traverse through all the values. List, tuples, dictionaries, and sets are all iterable objects.

To create an object as an iterator you have to implement the methods __iter__() and __next__() to your object where –

__iter__() returns the iterator object itself. This is used in for and in statements.

__next__() method returns the next value in the sequence. In order to avoid the iteration going on forever, raise the StopIteration exception.

Example

# define a list
my_list = [4, 7, 0, 3]

# get an iterator using iter()
my_iter = iter(my_list)

# iterate through it using next()

# Output: 4
print(next(my_iter))

# Output: 7
print(next(my_iter))

# next(obj) is same as obj.__next__()

Why use iterators?

Iterators allow us to create and work with lazy iterable which means you can use an iterator for the lazy evaluation. This allows you to get the next element in the list without re-calculating all of the previous elements. Iterators can save us a lot of memory and CPU time.

Python has many built-in classes that are iterators, Example, enumerate, map, filter, zip and reversed, etc. Objects are iterators