Learn Python
>>> control_flow.range

The range() Function in Python

#concept

range() generates a sequence of numbers on demand, most commonly used to control how many times a for loop repeats. It doesn't build a full list in memory up front — it produces each number one at a time as the loop asks for it, which makes it efficient even for very large ranges.

#how it works
1

range(stop)

Produces numbers from 0 up to, but not including, stop.

2

range(start, stop)

Produces numbers from start up to, but not including, stop.

3

range(start, stop, step)

Adds a step size, which can also be negative to count downward.

4

Values are produced lazily

One at a time, rather than building the whole sequence in memory first.

5

list(range(...)) forces all values at once

Mainly useful for inspecting a range directly, not needed inside an actual loop.

#example
print(list(range(5)))
print(list(range(2, 8)))
print(list(range(10, 0, -2)))
Output
[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7]
[10, 8, 6, 4, 2]
1range(5) with one argument starts at 0 by default, producing 0 through 4 — five numbers, stopping before 5.
2range(2, 8) with two arguments starts at 2 and stops before 8.
3range(10, 0, -2) counts downward from 10, stepping by -2 each time, and stops before reaching 0.
4Wrapping each in list() forces range to produce all its values at once so print() can display them — inside an actual for loop, this conversion isn’t needed.
#complexity
time O(1) per step
space O(1)

range() doesn't precompute or store its numbers — it generates the next one on demand, so even range(10_000_000) uses almost no memory, unlike building the equivalent list upfront.

#use cases
Controlling exactly how many times a for loop repeats
Generating indices to access list items by position inside a loop
Counting backward, or in steps other than 1, without manually tracking a counter variable
Efficiently representing a large sequence of numbers without storing them all in memory at once

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.