Skip to contentSkip to navigation

Module 1 of 6, Python in Depth

Iterators and Generators

See how a for loop really works, and produce values lazily with generators and itertools.

module checksSign in to track

  • Lessons complete-, not done
  • Lesson quizzes taken-, not done
  • Module Labs passed-, not done
  • Module exam passed at 80%-, not done
lessons
4
quiz questions
48
reading time
35 min
exam length
15 Q
coding exercises
6

Lessons

  1. Iterators and the Iteration ProtocolSee what a for loop really does: iterables and iterators, iter() and next(), StopIteration, one-shot iterators, and writing your own iterator class, with a first look at yield. 9 min 12 questions
  2. Generator Expressions and Lazy EvaluationBuild iterators in one line with generator expressions, feed them straight into sum, any, all, max and next, and chain them into lazy pipelines that handle big data in small memory. 9 min 12 questions
  3. Generator Functions and yieldWrite generators with full function bodies: how yield pauses and resumes, keeping state between items, endless generators, yield from, and pipelines of small generator functions. 8 min 12 questions
  4. itertools: Building Blocks for IteratorsUse the itertools module's fast, lazy tools: endless count and cycle, islice, chain, accumulate, pairwise and batched, grouping with groupby, and combinations, permutations and product. 9 min 12 questions

Lab: write it yourself

Real Python, real checks: write your answer, press Run checks, and keep going until it passes. (2 exercises)

All module exercises

The Lab needs an account. Sign in or create a free ID to run these exercises.

Lab 1: Generator countdown

Sign-in required

Write a generator function down_to_zero(n) that yields numbers from n down to 0. Print: [3, 2, 1, 0].

Sign in to practise

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.

Lab 2: Itertools cycle & islice

Sign-in required

Use itertools.cycle([1, 2]) and itertools.islice to take the first 5 elements. Print: [1, 2, 1, 2, 1].

Sign in to practise

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.

References & Further Reading

Related entries from PyLabs's own reference library.

  • iter() (Return an iterator for a collection or other iterable.)
  • next() (Get the next item from an iterator.)