Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 149 ยท Control Flow

range()

Master Python's range(). Count with start, stop and step, loop backward, understand why the stop value is excluded, and see why range objects use almost no memory.

A for loop needs something to iterate over. When what you need is simply "a bunch of numbers", such as repeating an action 10 times, counting from 1 to 100 or stepping through every other year, you don't have to type a list of numbers by hand. Python's built-in range() produces them for you.

range() looks simple, but it has a few rules worth learning precisely: the stop value is never included, the step can be negative, and a range is not a list but a lightweight object that calculates its numbers on demand. Once these click, you'll use range() confidently for counting, stepping and counting down.

range(stop): counting from zero

The simplest form takes one argument, the stop value. It produces whole numbers starting at 0, going up by 1, and stopping before stop:

Python Repeat something n times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

range(5) gives 0, 1, 2, 3 and 4: five numbers, but not 5 itself. When you don't need the number at all and just want to repeat something, name the loop variable _. That's a Python convention meaning "I'm ignoring this value".

Why is stop excluded?

The "up to but not including" rule seems odd at first, yet it has real benefits:

  • range(n) produces exactly n numbers.
  • The numbers match the valid indexes of a list with n items: 0 to n โˆ’ 1.
  • Ranges join cleanly: range(0, 5) and range(5, 10) cover 0 to 9 with no gap and no overlap.
  • The length of range(start, stop) is simply stop - start (for a positive step).

You'll see the same convention in slicing, so learning it once pays off twice.

range(start, stop): choosing where to begin

With two arguments, the first is where counting starts (included) and the second is where it stops (excluded):

Python Starting somewhere else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

To include a number, make stop one larger than it. A range where start is already at or past stop (counting upward) is empty: a loop over it runs zero times, and Python doesn't raise an error.

list(range(...)) turns a range into a list so you can see all its numbers at once. It's handy for experimenting, but you rarely need it in real loops.

range(start, stop, step): skipping and counting down

The optional third argument, step, is the amount added each time. It defaults to 1.

Python Steps and countdowns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The rules for a negative step mirror the positive ones: the range starts at start, keeps going while the number is still greater than stop, and never includes stop itself. That's why range(10, 0, -1) stops at 1. To count down to 0 inclusive, write range(10, -1, -1).

A step of 0 makes no sense (the numbers would never change), so range(1, 10, 0) raises ValueError: range() arg 3 must not be zero.

Tip: To loop backward over an existing sequence, reversed() is often clearer than a negative range. for n in reversed(range(1, 6)) gives 5, 4, 3, 2, 1, and for name in reversed(names) walks a list from the end.

Arguments must be integers

range() accepts only whole numbers. range(0, 1, 0.1) raises a TypeError. To step through decimals, loop over integers and scale them:

Python
for i in range(5):
    x = i / 10        # 0.0, 0.1, 0.2, 0.3, 0.4
    print(x)

Range objects are lazy

Calling range() doesn't build a list of numbers. It creates a small range object that remembers just three values (start, stop and step) and works out each number when it's needed. That makes a range of a billion numbers take the same tiny amount of memory as a range of three.

Python Exploring a range object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A range supports many of the same operations as a list:

  • len(r) gives how many numbers it contains.
  • Indexing works, including negative indexes: r[0], r[-1].
  • in checks membership, and for integers it's instant, because Python computes the answer with arithmetic instead of searching.
  • Slicing a range returns another range: range(10)[2:6] is range(2, 6).
  • Two ranges are equal if they produce the same numbers: range(0, 3) == range(0, 3, 1) is True.

What you can't do is change it. Ranges are immutable, so there's no append() or item assignment. When you need a real, changeable list of numbers, convert with list(range(...)).

Common range patterns

Here are the situations where range() is the natural tool:

Python Everyday uses of range()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pattern 4 is a legitimate use of indexes: you need positions to reach the next item. But resist range(len(items)) when you only want each item, or each item with its position. Those cases have better tools:

You want Prefer Instead of
Each item for item in items for i in range(len(items)): items[i]
Each item and its index for i, item in enumerate(items) range(len(items)) plus indexing
Items from two lists together for a, b in zip(xs, ys) for i in range(len(xs)): xs[i], ys[i]

Using the right tool removes off-by-one errors, the classic bug where a loop runs one time too many or too few.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which numbers does range(3, 8) produce?

    The start value is included and the stop value is excluded.
  2. 2. How do you write a loop that counts 5, 4, 3, 2, 1?

    With a step of -1 the range counts down and stops before 0, so the last number is 1. Without a negative step, range(5, 0) is empty.
  3. 3. What does list(range(10, 3)) give?

    The default step is +1, and you can't count up from 10 to 3, so the range is empty. No error is raised.
  4. 4. Why does range(1_000_000_000) use almost no memory?

    Range objects are lazy. They never hold all their numbers at once, which is also why len(), indexing and in are fast.
  5. 5. Which call raises an error?

    All range arguments must be integers, so a float step raises a TypeError. The others are valid (range(0) is simply empty).

Summary

  • range(stop) counts from 0 up to, but not including, stop, so it yields exactly stop numbers.
  • range(start, stop) begins at start; range(start, stop, step) adds step each time.
  • A negative step counts down and still excludes stop: range(10, 0, -1) ends at 1.
  • Ranges that can't reach stop are empty rather than errors; a step of 0 or a non-integer argument is an error.
  • A range is a lazy, immutable object: tiny in memory, with fast len(), indexing, slicing and in.
  • Use _ as the loop variable when you don't need the number, and prefer enumerate() or zip() over range(len(...)) when you're really after items.

Next: Lists, the most-used way to store a changeable sequence of values in Python.