Python Iterators

🐍 Python Iterators

An iterator is an object that allows you to iterate (loop) through a sequence of values—such as strings, lists, tuples, etc.

Iterators are used when you want to process items one at a time.


✅ What Makes an Object Iterable?

An object is iterable if:

  • It can return items one by one

  • It contains the method __iter__()

Examples: list, tuple, string, set, dict

my_list = [10, 20, 30]

print(iter(my_list)) # returns iterator object


 What is an Iterator?

An iterator is an object that implements:

Method Purpose
__iter__() Returns the iterator object
__next__() Returns the next value

Example: Using Iterator Manually

numbers = [1, 2, 3]
it = iter(numbers)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3

If you call next() again, you get:

StopIteration Error

 Using Iterators in Loops

Instead of writing next() manually, Python automatically uses iterators inside loops:


 


 String as an Iterator


 


🧠 Creating Your Own Iterator Class

You can create a custom iterator by defining the two required methods:


 

Output:

1
2
3
4
5

 Infinite Iterators

You can create infinite iterators (no stopping condition).
Use carefully to avoid infinite loops.


 


 Iterator vs Iterable (Quick Difference)

Feature Iterable Iterator
Can be looped ✅ Yes ✅ Yes
Needs __iter__() ✅ Yes ✅ Yes
Needs __next__() ❌ No ✅ Yes
Examples list, tuple, str iter(list)

 Why Use Iterators?

✔ Saves memory (values created one at a time)
✔ Useful for large datasets
✔ Used in loops, generators, and file reading


🧠 Real Example: Reading Files with Iterator


 

Python reads one line at a time → efficient for large files.


📌 Summary

  • Iterators let you loop through values one at a time.

  • Any object with __iter__() is iterable.

  • Iterator object must also have __next__().

  • Best used for large data and memory-efficient looping.


🚀 Practice Exercises

  1. Create an iterator that prints numbers from 1 to 20.

  2. Make a countdown iterator starting from 10 to 1.

  3. Create an iterator that returns even numbers only.

  4. Convert a string into an iterator and print characters using next().

You may also like...