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

Python range()

range() makes a counting sequence of numbers for you, like a coach counting off one, two, three. You tell it where to start, where to stop and how big each step is.
Syntax
python
range(stop)
range(start, stop)
range(start, stop, step)

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)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting range(1, 5) to include 5; the stop value is excluded.
  2. Passing a float such as range(2.5), which raises TypeError; range accepts only integers.
  3. Printing range(5) and expecting a list; you get range(0, 5) and need list(range(5)).

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.