Module lessons (1/4)
for loops and range()
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 thefor item in iterableconstruct. - Generate lazy number sequences with
range(start, stop, step)inO(1)space. - Match indices with
enumerate(..., start=...)and iterate through multiple sequences in parallel withzip(...).
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
- 1The mental model: cursor on a lazy iterator
- 2Scroll through sequences and
range(start, stop, step) - 3Clean indexes with
enumerateand parallel iteration withzip - 4Quick check
- 5Test yourself
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.