← Back to Python Course | Chapter 3: Control Flow | Lesson 9 of 10

Python range()

range() with One Argument

range(stop) produces a sequence of numbers starting at 0 and going up to, but not including, stop — so range(5) yields 0, 1, 2, 3, 4, exactly five values. This single-argument form is the most common way to repeat a block of code a fixed number of times.

Example: range() with One Argument

python
print(list(range(5)))

range() with Start and Stop

range(start, stop) begins counting at start instead of 0, which is useful whenever your sequence needs to begin at a specific number, like generating IDs starting from 1 or looping from a given index onward.

Example: range() with Start and Stop

python
print(list(range(2, 6)))

range() with a Step

The third argument to range() sets the increment between values, so range(0, 10, 2) yields only even numbers, and a negative step like range(10, 0, -1) counts downward — the stop value is still never included even when counting backward.

Example: range() with a Step

python
print(list(range(0, 10, 2)))
print(list(range(10, 0, -1)))

range() Is Lazy

Unlike a list, range() doesn't actually store every number in memory at once — it's a lazy sequence that computes each value only as it's needed, which is why range(1000000000) creates instantly and uses almost no memory instead of allocating a billion-element list.

Example: range() Is Lazy

python
r = range(1000000000)
print(type(r))

range() in List Comprehensions

range() is frequently paired with a list comprehension to build a transformed sequence in one line, such as squaring every number in a range, which is more concise than writing an explicit for loop with append() calls.

Example: range() in List Comprehensions

python
squares = [x * x for x in range(5)]
print(squares)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.