Skip to content
    SeaCode
    Learning tracksCode ArenaWorkshops & EventsInstructors
    Log inSign up
    PyPython

    Getting started

    • Your first Python program
    • Variables and types
    • Numbers and operators
    • Type conversion and input

    Strings

    • Strings and f-strings
    • String indexing and slicing
    • Cleaning and splitting strings

    Control flow

    • Conditions: if, elif and else
    • Loops: for and while
    • Loop control and nesting

    Functions

    • Functions with def
    • Parameters and scope

    Collections

    • Lists
    • Dictionaries
    • Tuples and sets
    • Comprehensions, enumerate and zip

    Errors, files and libraries

    • Handling exceptions
    • Modules and the standard library
    • Reading and writing files
    • Exchanging data with JSON

    Objects and lazy iteration

    • Classes and objects
    • Inheritance and composition
    • Iterators and generators

    Testing and project

    • Testing and project setup
    • Project: a grade report
    Python

    Objects and lazy iteration · Lesson 23 of 25

    Iterators and generators

    Produce values one at a time with yield.

    8 minutes2 games

    An iterable can be traversed; an iterator tracks its current position. iter() obtains an iterator and next() advances it. A function containing yield returns a generator that resumes where it paused each time a value is requested.

    Python
    def squares(limit):
        for n in range(limit):
            yield n * n
    
    values = squares(3)
    print(next(values))
    print(list(values))
    print(list(values))

    Request next

    Run until yield

    Yield value and pause

    Resume on next request

    Important

    A generator is consumed; it does not restart after exhaustion. Create a fresh generator for another traversal.

    Interview question

    When can a generator save memory?

    What's the output?

    values = (n * 2 for n in range(3))
    print(next(values))
    print(next(values))

    What will this code print?

    Exercise

    Create a generator yielding 3, 2, 1 and print it as a list.

    Expected output: [3, 2, 1]

    Python

    Learn more from

    • Python documentationdocs.python.org
    • Real Python: further readingrealpython.com

    Played 0 of 2 games

    Sign in to save your progress and earn XP.

    PreviousInheritance and compositionNextTesting and project setup
    SeaCode

    Learn to code for real, online or at our branch in front of Cairo University, Giza.

    Learn

    • All courses
    • Interactive tutorials
    • Interview practice problems
    • Mock interview
    • Learning tracks
    • Code Arena
    • Workshops & Events
    • Knowledge library
    • Team projects

    Your account

    • Log in
    • Sign up
    • Learning plan
    • Certificates
    • Site map

    Contact us

    • WhatsApp
    • 010 9094 1104
    • In front of Cairo University, Giza

    © 2026 SeaCode. All rights reserved.