site logo

Learn to Python. Build the Future.


Category: (All)
❮  Go Back

06. Deep Dive into Python Iterators and Polymorphism

Introduction

Python has elegant mechanisms for both iteration and polymorphism. Iterators let you traverse data in a controlled way, while polymorphism allows code to handle different types uniformly. Understanding these concepts strengthens your ability to build flexible, efficient, and reusable Python programs.


Python Iterators

What Is an Iterator?

An iterator is an object that enables you to traverse through all the elements of a collection (like lists, tuples, strings) one at a time. It implements the iterator protocol, meaning it defines two methods: __iter__() and __next__().

  1. __iter__() returns the iterator object itself.
  2. __next__() returns the next item. When there are no more items, it should raise StopIteration.


Creating and Using Iterators

You can get an iterator from any iterable (list, tuple, string) using the built-in iter() function:

mylist = [1, 2, 3]
it = iter(mylist)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
# next(it) now would raise StopIteration

Under the hood, Python’s for loop uses iterators: for each iteration it calls __next__() until StopIteration is raised.


Custom Iterators

You can build your own iterator by defining a class with the two required methods:

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myiter = iter(MyNumbers())
print(next(myiter)) # 1
print(next(myiter)) # 2

To prevent infinite iteration, include logic in __next__() to raise StopIteration when a condition is met.


Why Use Iterators?

  1. Memory efficiency — items are generated one at a time, not stored all at once.
  2. Lazy evaluation — values are produced only when needed.
  3. Uniform interface — many Python constructs (loops, comprehensions, built-ins) expect iterators.


Python Polymorphism

What Is Polymorphism?

Polymorphism literally means “many forms.” In programming, it allows functions, methods, or operators to work with different object types and respond differently according to the object.


How Polymorphism Appears in Python

Operator Polymorphism

The same operator works differently depending on types. For example:

  1. + can sum integers
  2. + can concatenate strings
  3. + can merge lists

This is operator overloading in action.


Function Polymorphism (Duck Typing)

Built-in functions like len() can operate on strings, lists, tuples, or dictionaries — returning the appropriate measure depending on the object type.


Method Polymorphism via Inheritance

In OOP, subclasses can override methods defined in a parent class, so that a method call behaves differently depending on the object’s class.

Example:

class Animal:
def sound(self):
print("Some generic sound")

class Dog(Animal):
def sound(self):
print("Bark")

class Cat(Animal):
def sound(self):
print("Meow")

animals = [Dog(), Cat(), Animal()]
for a in animals:
a.sound() # Output: Bark, Meow, Some generic sound

Here sound() takes on different behavior depending on the object type.


Benefits of Polymorphism

  1. Promotes code reusability
  2. Allows more flexible and extendable code
  3. Enables writing generic interfaces — you can call the same method name on different object types


Things to Keep in Mind

  1. Python does not support method overloading (same method name with different signatures) explicitly. Instead, you can use default or variable arguments to achieve similar behavior.
  2. Ensure that overridden methods maintain expected interface so client code doesn’t break.


Conclusion

Iterators and polymorphism are foundational Python concepts that empower more expressive, maintainable, and scalable code. Iterators give you a standard way to traverse data without consuming memory upfront. Polymorphism gives you flexibility — allowing objects to respond to the same interface in different ways. Master these, and your Python skills will rise to a new level.

06. Deep Dive into Python Iterators and Polymorphism

coldshadow44 on 2025-10-11



(0)





Showing comments related to this post.




Member's Sites: