IDRASAcademic OS
Unit 6: Module 6: CPython PyObject Memory Model, Ref Counting & Heap Pointers 25 mins study timeBASIC

Python Loops, range(), Iterables & Loop-Else Mechanics

In-depth breakdown of Python's iteration protocol, lazy generator mechanics of range(), loop control statements, and the loop-else paradigm.

Verified: Karann

Learning Objectives

  • •Deconstruct Python's iteration protocol and distinguish between iterables and iterators.
  • •Analyze why range() in Python 3 operates in O(1) memory complexity.
  • •Trace loop execution step-by-step with state transitions matching IDRAS Section 28.
  • •Implement search algorithms cleanly using the Python 'for...else' idiom.

Essential Prerequisites

  • •Basic variable assignment
  • •Boolean condition evaluation
Layer 1: Intuition & Why It Matters

The Core Mental Model

“Think of an iterable as a book on a shelf, and an iterator as a bookmark that remembers exactly which page you are on. When you call next(), the bookmark slides to the next page.”

Why This Exists

Every software engineering workload depends on iteration. Understanding how Python handles iterators natively prevents memory crashes.

Beginner Foundation

Unlike languages like C where you write 'for(int i=0; i<n; i++)', Python loops directly over items: 'for item in collection'.

Micro Concepts Decomposition

MICRO CONCEPT 1Canonical Object

The Iteration Protocol: __iter__() and __next__()

In Python, a for-loop does not use index counter arithmetic (like C). Instead, it calls iter(obj) to obtain an iterator, then repeatedly invokes next(it) until a StopIteration exception is raised.

Key Takeaway: Any object implementing __iter__() is an iterable; any object implementing __next__() is an iterator.
MICRO CONCEPT 2Canonical Object

The range() Generator & Memory Efficiency

In Python 3, range(start, stop, step) is an immutable sequence type that produces numbers on demand. Regardless of whether you specify range(10) or range(10_000_000), it consumes only 48 bytes of memory.

Key Takeaway: range() is a lazy sequence, calculating values on-the-fly via O(1) arithmetic without allocating arrays in RAM.
MICRO CONCEPT 3Canonical Object

Control Flow: break, continue, and pass

'break' immediately terminates the innermost enclosing loop. 'continue' skips the rest of the current iteration and advances to the next step. 'pass' is a syntactic no-operation placeholder.

Key Takeaway: break terminates; continue skips to next iteration; pass does nothing.
MICRO CONCEPT 4Canonical Object

The 'for...else' Construct & Search Patterns

The 'else' block attached to a for or while loop executes ONLY if the loop finishes naturally without encountering a 'break' statement. It is designed specifically for search completion without extra flag variables.

Key Takeaway: Loop 'else' means 'nobreak' — it executes only when no break was triggered during execution.
Layer 3 & 4: Formal Specification & Mechanism

Hardware State Machine Architecture

At CPython bytecode level, 'for item in sequence' compiles into GET_ITER and FOR_ITER opcodes.
Step-by-step Execution Walkthrough (for i in range(3)): Step 1: iter(range(3)) created. Internal index = 0. Step 2: next() returns 0. i bound to 0. Body executes. Step 3: next() returns 1. i bound to 1. Body executes. Step 4: next() hits end -> raises StopIteration -> caught cleanly -> loop terminates.
Layer 7: Interactive Laboratory

Interactive Simulator

PYTHON • VISUALIZATIONPython Memory Model & PyObject Pointer Laboratory
Launch Fullscreen Lab
PYTHON • MEMORY INTERNALSPyObject & Reference Semantics

Python Object Identity (`is`), Equality (`==`) & PyObject Pointer Laboratory

Call Stack Frame (Names / Pointers)
Variable a→ Pointer: 0x7f1a000
Variable b→ Pointer: 0x7f1a000
CPython Heap (PyObject Headers)
Address: 0x7f1a000refcnt: 2
PyLongObject: 100
Equality (`a == b`)
True
Compares values
Identity (`a is b`)
True
Compares memory addresses `id(a) == id(b)`
Python CPython Architecture Insight:

Python pre-allocates an internal array of integer objects for values between -5 and 256 at interpreter startup. When you assign any integer in this range, Python points to the cached singleton PyObject rather than allocating a new object on heap!

Layer 5: Step-by-Step Worked Numerical Example

End-to-End Execution Trace

Trace table of for i in range(3).
Layer 6: Active Runtime CodeLab

Step-by-Step Code Execution (PYTHON)

SQL Studio
Font
main.pyGlacier Light
Ln 1 • Python 3.12
1
2
3
4
5
82 chars • 5 lines • Ln 1UTF-8 • 4 Spaces
Interactive Terminal Shell

Sandbox Terminal Ready

Click Run Code or press Ctrl+Enter to compile and execute.

⚡ AURXON Bitstream Runtime v4.8IDRAS Academic Virtual Node
Common Student Pitfalls & Mistakes

Where Students Lose Marks

❌ Mistake: Mutating list while iterating
✓ Correct Understanding:
❌ Mistake: Confusing range() memory usage
✓ Correct Understanding:
Layer 8: Practice & Knowledge Verification

Active Assessment Quiz

Interactive Assessment EngineQuestion 1 of 1

Python Loops, range(), Iterables & Loop-Else Mechanics — Practice Questions

BASIC LevelScore: 0/0

What is the exact output of this Python code snippet?

for i in range(3):
    if i == 5:
        break
else:
    print("DONE")
Academic Evaluation Preparation

Viva Examination & University Scoring Strategy

Standard Viva Examination Questions

Q1: How does range() in Python 3 differ from range() in Python 2?
Answer: In Python 2, range() generated an entire list in memory, while xrange() was a generator. In Python 3, range() is an immutable sequence generator type that produces values lazily in O(1) memory.
Q2: What exception signals the termination of an iterator?
Answer: The StopIteration exception, which is caught and handled automatically by for-loops and comprehension expressions.

How to Write High-Scoring University Exam Answers

Explain the Python iteration protocol: iter() and next() functions. Define range(start, stop, step) syntax and its lazy evaluation mechanism. Illustrate the control flow of break, continue, pass. Provide a flow diagram of the for...else construct and contrast it with traditional boolean flag search implementations.