Module 3 · Loops in Python · Lesson 3 of 6
The range() function
Counting is so common in loops that Python has a function just for it: range(). It produces a sequence of numbers on demand — perfect for repeating something a fixed number of times.
range(5)stop only — starts at 0range(2, 6)start, stoprange(1, 10, 2)start, stop, stepThe stop value is never included — range(5) stops before 5.
It takes up to three numbers. With one, range(5) counts from 0 up to (but not including) 5. With two, range(2, 6) sets the start and stop. With three, range(1, 10, 2) adds a step — here, every second number.
The one rule that catches people out: the stop is never included. range(5) gives you five numbers — 0, 1, 2, 3, 4 — and stops just before 5. That's actually convenient: range(len(...)) lines up perfectly with counting positions, which you'll use all the time with lists.
Two notes: a negative step counts down (handy for a countdown), and range() doesn't build the whole list in memory — it hands out numbers one at a time as the loop asks for them. Wrap it in list() if you want to see them all at once.