Hackforge Academy

Category: python

Introduction to Iterators

Published on 24 Jul 2026

Explanation

An iterator is an object that allows you to traverse through the elements of a collection one element at a

Code:

numbers = [10, 20, 30, 40, 50]

iterator = iter(numbers)

print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))

# Using a loop
for number in numbers:
    print(number)

Explanation

A generator is a special type of function that returns values one at a time using the yield keyword instead

Code:

def number_generator():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5

numbers = number_generator()

print(next(numbers))
print(next(numbers))
print(next(numbers))

for number in numbers:
    print(number)

Explanation

A generator expression is a concise way to create generators using syntax similar to list comprehensions. Instead of square brackets

Code:

numbers = (num * num for num in range(1, 11))

for value in numbers:
    print(value)

# Sum of squares
result = sum(num * num for num in range(1, 6))
print('Sum of Squares:', result)

Explanation

A decorator is a function that extends or modifies the behavior of another function without changing its original code. Decorators

Code:

def welcome_decorator(function):

    def wrapper():
        print('Welcome!')
        function()
        print('Thank You!')

    return wrapper


@welcome_decorator
def display():
    print('Learning Python Decorators')


display()

Explanation

Iterators, generators, and decorators are powerful Python features commonly used in production applications. Iterators simplify traversing collections, generators efficiently process

Code:

import time


def timer(function):

    def wrapper(*args, **kwargs):
        start = time.time()
        result = function(*args, **kwargs)
        end = time.time()
        print('Execution Time:', round(end - start, 4), 'seconds')
        return result

    return wrapper


@timer
def generate_squares(limit):
    for number in range(1, limit + 1):
        yield number * number


for square in generate_squares(10):
    print(square)

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community