Python Iterators


An iterator is an object that contains a countable number of values and can be iterated upon, meaning you can traverse through all the values.


🔹 What is an Iterator?

In Python, an object is an iterator if it implements two methods:

  • __iter__()

  • __next__()


🔹 Using iter() and next()

Most built-in containers like lists, tuples, dictionaries, and sets are iterable, which means you can get an iterator from them.

fruits = ["apple", "banana", "cherry"]
it = iter(fruits)

print(next(it))  # apple
print(next(it))  # banana
print(next(it))  # cherry

🔹 Loop Through an Iterator

You can loop through an iterator using a for loop:

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

for fruit in fruits:
    print(fruit)

✅ Internally, the for loop uses iter() and next().


🔹 Create Your Own Iterator

To create a class-based iterator, define both __iter__() and __next__().

class Counter:
    def __init__(self):
        self.x = 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.x <= 5:
            result = self.x
            self.x += 1
            return result
        else:
            raise StopIteration

my_counter = Counter()
for num in my_counter:
    print(num)

🔹 The StopIteration Exception

When there are no more items to return, the iterator must raise StopIteration to signal the end.


🔹 Difference Between Iterable and Iterator

Term Description
Iterable Object you can loop over (list, tuple)
Iterator Object with __next__() method

Practice Questions

Q1. Write a Python program to use iter() and next() to print each item from a tuple.

Q2. Write a Python program to create a list of 3 names and iterate through them using next() and iter().

Q3. Write a Python program to use a for loop to print numbers from an iterable (e.g., a range or list).

Q4. Write a Python program to build a custom iterator class that returns the squares of numbers up to 5.

Q5. Write a Python program to modify your iterator to raise StopIteration after 3 elements are returned.

Q6. Write a Python program to convert a string into an iterator and print each character one by one.

Q7. Write a Python program to create a countdown iterator that returns numbers from 5 to 1.

Q8. Write a Python program to make a custom iterator that returns only even numbers up to 10.

Q9. Write a Python program to use an iterator to read a file line by line.

Q10. Write a Python program to create an iterator that returns Fibonacci numbers up to 10.


Go Back Top