An iterator in Python is an object that allows sequential traversal (iteration) of elements from a collection such as a list, tuple, set, or dictionary — one item at a time.

Iterators provide a way to access elements without using indexing, and are fundamental to Python’s looping constructs like for loops.


🔹 Key Concepts

ConceptDescription
IterableAny object that can return an iterator using iter(). Examples: list, tuple, dict, set, str.
IteratorAn object that produces data one element at a time using the next() function.
IterationThe process of going through elements of an iterable using an iterator.
StopIterationAn exception raised automatically when no more elements are left to iterate.

🔹 Iterator Protocol

An object is an iterator if it implements the following two methods:

  1. __iter__() → returns the iterator object itself.
  2. __next__() → returns the next value from the data source.

When there are no more items, __next__() raises a StopIteration exception.


🧩 Example 1: Using iter() and next()

numbers = [1, 2, 3, 4]
iterator = iter(numbers)   # Create an iterator object

print(next(iterator))  # 1
print(next(iterator))  # 2
print(next(iterator))  # 3
print(next(iterator))  # 4

Output:

1
2
3
4

(If you call next(iterator) again → it raises StopIteration.)


🧩 Example 2: Iterating Using a for Loop

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:  # Internally uses iter() and next()
    print(fruit)

Output:

apple
banana
cherry

Explanation:
The for loop automatically:

  1. Calls iter(fruits) to get an iterator.
  2. Repeatedly calls next() until StopIteration is raised.

🧩 Example 3: Creating a Custom Iterator Class

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self  # Returns itself as iterator

    def __next__(self):
        if self.current > self.high:
            raise StopIteration
        else:
            num = self.current
            self.current += 1
            return num

for i in Counter(1, 5):
    print(i)

Output:

1
2
3
4
5

🧩 Example 4: Using Iterators with Strings

word = "Dheeraj"
it = iter(word)

print(next(it))
print(next(it))
print(next(it))

Output:

D
h
e

🧩 Example 5: Handling StopIteration Exception

nums = [10, 20]
it = iter(nums)

try:
    print(next(it))
    print(next(it))
    print(next(it))  # No more elements
except StopIteration:
    print("End of iteration reached")

Output:

10
20
End of iteration reached

🔹 Difference Between Iterable and Iterator

FeatureIterableIterator
DefinitionObject that can return an iterator using iter().Object that produces elements one by one using next().
Exampleslist, tuple, dict, str, setObjects returned by iter() function.
MethodsHas __iter__() method.Has both __iter__() and __next__() methods.
UsageUsed in loops like for or comprehension.Used when you need manual iteration with next().

🔹 In Summary

  • An iterator is an object that represents a stream of data.
  • It uses the iter() and next() functions to traverse items one by one.
  • for loops internally use the iterator protocol.
  • Custom iterators can be created by defining __iter__() and __next__() methods.
  • When no more data is available, a StopIteration exception is raised.

In short:

Iterator = object that remembers where it is during iteration and fetches next data only when requested.


Scroll to Top