Python Iterators

🐍 Python Iterators β€” Full Tutorial

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:

numbers = [1, 2, 3]

for num in numbers:
print(num)


πŸ”Ή String as an Iterator

word = "Python"

it = iter(word)

print(next(it)) # P
print(next(it)) # y
print(next(it)) # t


🧠 Creating Your Own Iterator Class

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

class Counter:
def __iter__(self):
self.num = 1
return self
def __next__(self):
if self.num <= 5:
value = self.num
self.num += 1
return value
else:
raise StopIterationcounter = Counter()

for i in counter:
print(i)

Output:

1
2
3
4
5

πŸ”Ή Infinite Iterators

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

class InfiniteCounter:
def __iter__(self):
self.num = 1
return self
def __next__(self):
self.num += 1
return self.numit = InfiniteCounter()

for i in it:
print(i)
if i == 10:
break


πŸ”Ή 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

file = open("sample.txt")

for line in file:
print(line)

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().

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *