Skip to main content
Module 2 · Lesson 1 of 45/36 in the course~14 min
Module lessons (1/4)

for loops and range()

Lesson preview5 hands-on exercises readyPython Course · Module 2 — Control flow

Iterating over sequences with for and generating numeric ranges with range(start, stop, step).

What you'll learn in this lesson

  • Iterate through any iterable (list, str, tuple, dict) with the for item in iterable construct.
  • Generate lazy number sequences with range(start, stop, step) in O(1) space.
  • Match indices with enumerate(..., start=...) and iterate through multiple sequences in parallel with zip(...).

Overview

In Python for is not a C-style counter (for (int i = 0; i < n; i++)): it is always a for-each on the iterator protocol. Whether it's a list, a string, or a range, the mechanism is identical: it asks for one element at a time until the source runs out.

Functions like range(), enumerate() and zip() don't build huge lists in RAM: they return lazy objects that produce the next value only at the requested step of the loop, keeping the memory footprint constant (O(1)).

Sections covered in this lesson

  1. 1The mental model: cursor on a lazy iterator
  2. 2Scroll through sequences and range(start, stop, step)
  3. 3Clean indexes with enumerate and parallel iteration with zip
  4. 4Quick check
  5. 5Test yourself
Pro Lesson · Module 2 — Control flow

Unlock "for loops and range()" and the full Python Course curriculum

Iterating over sequences with for and generating numeric ranges with range(start, stop, step).

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Python Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.