Beginner   Chapter 65 · 25 min read · Module 5: Control Flow

range() Function

Learning objectives
  • After this chapter you can use range() with one, two or three arguments.
  • You can predict the numbers that a range produces, including the excluded stop value.
  • You can count backwards using a negative step.
  • You can turn a range into a list and use len() and in on it.
  • You can use range() to loop a fixed number of times or over list positions.

The range() function gives you a sequence of whole numbers. It is the usual partner of the for loop whenever you want to repeat something a fixed number of times or count through numbers such as 1 to 10.

A range does not store all of its numbers in memory. It calculates each number only when needed, so even range(1000000) is very small and fast to create. In Python 3 it is its own type, called range, not a list.

In this chapter you will learn the three forms of range(), the rule that the stop value is excluded, how to count backwards, and some useful patterns for real programs.

The three forms

FormMeaningExample result
range(stop)0 up to stop-1range(4) -> 0, 1, 2, 3
range(start, stop)start up to stop-1range(2, 5) -> 2, 3, 4
range(start, stop, step)jump by steprange(0, 10, 3) -> 0, 3, 6, 9

The most important rule is that the stop value is never included. This matches how list slices work. A helpful trick: range(a, b) has exactly b - a numbers in it.

Example 1: the stop is excluded
for i in range(5):
    print(i, end=' ')
print()
for i in range(2, 6):
    print(i, end=' ')
0 1 2 3 4 2 3 4 5
Step: the difference between one number and the next in a range. The default step is 1.

Using a step

The third argument is the step. A step of 2 gives every second number, which is how you get even numbers or odd numbers. The step cannot be zero; Python raises a ValueError for that.

Example 2: even numbers
for n in range(2, 11, 2):
    print(n, end=' ')
2 4 6 8 10

Counting backwards

For a countdown use a negative step. The start must then be larger than the stop, otherwise the range is empty. Remember that the stop value is still excluded, so to include 1 you stop at 0.

Example 3: countdown
for n in range(5, 0, -1):
    print(n, end=' ')
print('Go!')
5 4 3 2 1 Go!

Converting and inspecting a range

You can pass a range to list() to see its values. You can also use len(), the in operator, indexing and slicing on a range. These work without creating the full list in memory.

Example 4: range as an object
r = range(3, 20, 4)
print(list(r))
print(len(r), r[0], r[-1])
print(7 in r, 8 in r)
[3, 7, 11, 15, 19] 5 3 19 True False

Looping a fixed number of times

If you only need to repeat something and do not care about the number itself, name the variable _. This is a convention that tells readers the value is not used.

Example 5: repeat without using the value
for _ in range(3):
    print('Python')
Python Python Python

Looping over positions

Sometimes you need the position of each item, for example to change the list in place or to compare neighbours. Combine range() with len(). Be careful that the last valid index is len(items) - 1, which range(len(items)) handles correctly.

Example 6: neighbours
nums = [3, 8, 2, 9]
for i in range(1, len(nums)):
    print(nums[i - 1], 'then', nums[i])
3 then 8 8 then 2 2 then 9
If you only need the items, loop directly over the list. If you need index and item, enumerate() is often neater than range(len(items)).

Choosing good values

When you write a range, say in words what you want first. For example: I want the numbers from 10 down to 1. The first number is 10, the last number is 1, so the stop must be 0, and the step must be -1. Saying it aloud like this turns an abstract rule into a short checklist. Another check is to test with a very small case, such as range(1, 3), and list the result by hand. If your expectation matches the real output, you can trust the same pattern for larger values.

Ranges also work nicely with variables. If n holds the number of rows in a pattern, then range(n) repeats the work n times, and range(1, n + 1) lets you count from 1 to n. Because the values come from variables, the same program can handle small and large inputs without any change to the loop itself.

Typical patterns

  • Sum of 1 to n: sum(range(1, n + 1)).
  • Multiplication table: for i in range(1, 11): print(n, 'x', i, '=', n * i).
  • Every third item of a list: items[::3] or for i in range(0, len(items), 3).
  • Build a list of squares: [i * i for i in range(5)].

Arguments to range() must be integers. Writing range(2.5) or range(0, 1, 0.1) gives a TypeError. For decimal steps, calculate a value inside the loop, for example i / 10. Negative numbers are fine, so range(-3, 3) gives -3 up to 2.

Because the stop is excluded, a common off-by-one mistake is to forget to add 1 when you want the last number included. To print 1 to 10 you need range(1, 11), not range(1, 10).

Python syntax

Syntax
range(stop)
Syntax
range(start, stop)
Syntax
range(start, stop, step)
Syntax
for i in range(len(items)):
    body

Real-world applications

  • Repeating an action a fixed number of times.
  • Printing numbered lists and tables.
  • Accessing list items by position.
  • Generating test data such as 1 to 100.
  • Counting down timers or lives in games.

Common mistakes

Mistake: Expecting the stop value to be included.
Fix: Remember range(1, 5) ends at 4. Use range(1, 6) to include 5.
Mistake: Using a positive step with start larger than stop.
Fix: Use a negative step for counting down.
Mistake: Passing a float to range().
Fix: Use whole numbers and compute decimals inside the loop.
Mistake: Using a step of zero.
Fix: The step must be a non-zero integer.
Mistake: Printing a range and expecting its numbers.
Fix: Wrap it in list() to see the values.

Important tips

  • Check the length with len(range(a, b)).
  • Use _ when the number is not needed.
  • Prefer enumerate() when you need both index and item.
  • Test small ranges by converting to a list.

Key points summary

  • range() gives integers lazily.
  • The stop is excluded.
  • The default start is 0 and the default step is 1.
  • A negative step counts down.
  • range supports len, in, indexing and slicing.

Exam and interview points

  • range(5) is 0 to 4.
  • range(1, 10, 3) gives 1, 4, 7.
  • range(10, 0, -2) gives 10, 8, 6, 4, 2.
  • range objects are immutable sequences.
  • len(range(a, b)) equals max(0, b - a) for step 1.

Quick revision

  • range(stop).
  • range(start, stop).
  • range(start, stop, step).
  • Stop excluded.
  • Negative step counts down.

Frequently asked questions

Is range() a list?

No. In Python 3 it is a special sequence type that saves memory. Use list(range(...)) if you need a real list.

Why is the stop not included?

It makes lengths easy: range(a, b) has b - a items, and ranges can be joined without overlapping.

Can I use range with floats?

No. Only integers are allowed. Use a loop with division or a library such as NumPy for decimal steps.

What does an empty range look like?

range(5, 2) has no numbers, so a loop over it runs zero times.

Practise this chapter

18 practice questions Take the chapter quiz

Related chapters