What Are Python Iterators?

What Are Python Iterators?

Published on October 09 2023

In this tutorial, we will learn Python iterators and its application with an example. This tutorial is part of Python's top 25 most commonly asked interview questions.

Definition

  • Iterators are objects which can be traversed through or iterated upon.
  • In Python, iterators are used to iterate a group of elements, containers like a list, tuples, etc. (loop through an object and return its elements)
  • Python iterator implements
    • iter(): method initializes an iterator.
    • next(): method which returns the next item in iteration and points to the next element.
  • Upon reaching the end of the iterable object next() must return a StopIteration exception.

Example

data_list = [1, 2, 3, 4, 5]
my_iterator = iter(data_list)
print(next(my_iterator))
print(next(my_iterator))

Output

1
2

To know about it, please refer to the official documentation website - official website.