Iterable

Context: FIT1008_MOC · a collection that can produce an Iterator · makes LinkList work with for · enables List Comprehension

Quick Revision

  • 🎯 Objective: any object you can loop over ➔ produces a fresh Iterator on demand via iter.
  • 📦 Core Components: the Iterator design pattern — separate what to traverse from how.
  • ⚡ Key Constraint: __iter__ is ; traversal is the iterator’s — and can be lazy/infinite.

📝 Core

1. The Iterable (__iter__)

  • Produces ➔ a fresh Iterator each __iter__ call ➔ invoked by for, iter(), comprehensions, max, in.
  • Encapsulation ➔ traverse a LinkList with for item in a_list without touching head/link.
  • Pattern ➔ the Iterator pattern (GoF) — separates what to traverse from how.

2. Iterable vs Iterator

  • Iterable ➔ has __iter__ (yields a new iterator, re-iterable).
  • Iterator ➔ has __iter__ and __next__ (holds position, single-use).
  • One-way ➔ every iterator is iterable, but not conversely — a LinkList is iterable, not an iterator (no __next__).
  • Laziness ➔ iterator mediation lets an iterable be lazy/infinite (itertools.count(), a file, a Generator Expression).

⚙️ Core Implementation

🔹 __iter__ returns a fresh iterator

⚖️ Core Decision Matrix

PropertyIterableIterator
methods__iter____iter__ + __next__
holds position?noyes
re-iterable?yes (fresh each call)no (single-use)
can be lazy/infinite?yes (via its iterator)yes
exampleLinkList, str, rangeLinkListIterator, generator

When It Flips: encapsulation (traverse without internals) + uniformity (one syntax over lists, strings, ranges, trees, custom classes). Because elements come from the iterator's __next__ on demand, an iterable can represent an unbounded sequence in memory.

📊 Exam Execution Trace

Manual Execution Trace

What for x in a_list does:

Step / StateCall
0 (Init)
1it = a_list.__iter__() (fresh iterator)
2..nx = it.__next__() until…
endStopIteration → loop ends

Applied Exercise

Problem: Show iterable ⊇ iterator but not conversely. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: iterators are a strict subset of iterables — holding a cursor is the extra requirement.

🧠 Active Recall