Python range() Explained: Syntax, Examples, and Tips
In this article
Python's range() function generates a sequence of numbers, commonly used in for loops. It returns an immutable sequence type that produces numbers on demand, saving memory. You can call it with one, two, or three arguments: range(stop), range(start, stop), or range(start, stop, step). The function works in Python 3 and returns a range object, not a list. If you need a list, wrap it with list().
What You'll Need
- Python 3 installed on your computer (any recent version works).
- A text editor or Python IDE (like IDLE, VS Code, or PyCharm).
- Basic familiarity with running Python scripts or using the interactive shell.
Step-by-Step
- Understand the basic syntax. The simplest form is
range(stop). It generates numbers from 0 up to (but not including)stop. For example,range(5)produces 0, 1, 2, 3, 4. - Use it in a for loop. The most common use is iterating a fixed number of times:
This prints 0 through 4.for i in range(5): print(i) - Specify a start value. Use two arguments:
range(start, stop). The sequence begins atstartand ends beforestop. Example:range(2, 6)gives 2, 3, 4, 5. - Add a step value. The third argument controls the increment (or decrement) between numbers.
range(1, 10, 2)yields 1, 3, 5, 7, 9. A negative step counts downward:range(5, 0, -1)gives 5, 4, 3, 2, 1. - Convert to a list when needed. If you want to see the actual numbers or store them, use
list(range(4))which returns[0, 1, 2, 3]. This is useful for debugging or when you need to index into the result. - Check membership. You can test if a number is in a range using
in:5 in range(1, 10)returnsTrue. This is efficient because range checks are O(1). - Use range with len() for indexing. When you need to loop over a list by index, combine
range()withlen():
This prints each index and its corresponding color.colors = ['red', 'green', 'blue'] for i in range(len(colors)): print(i, colors[i]) - Note that range is lazy. The range object does not store all numbers in memory; it generates them on the fly. This makes it efficient even for huge ranges like
range(10**9). - Use it in list comprehensions. For example, gives [0, 1, 4, 9, 16] .
- Remember that range only works with integers. You cannot use floats as arguments. For decimal sequences, use
numpy.arange()or a while loop with a float counter.
Common Mistakes
- Forgetting that stop is exclusive.
range(10)does not include 10. This is the most frequent error. - Using a negative step without adjusting start and stop. If step is negative, start must be greater than stop. For example,
range(0, 5, -1)returns an empty range because you cannot go from 0 down to 5. - Expecting a list. In Python 3,
range()returns a range object, not a list. Printing it showsrange(0, 5), not the numbers. Uselist()to see them. - Using floats.
range(0.5, 5)raises aTypeError. Only integers are allowed. - Assuming range() is a generator. It is a sequence type, not a generator. It supports
len(), indexing, and membership tests, which generators do not.
Tips
- Use
enumerate()instead ofrange(len())when you need both index and value. It is cleaner:for i, color in enumerate(colors):. - For large ranges, prefer
range()overlist(range())to save memory. Only convert to a list when you actually need the list. - Use
range()to repeat an action a specific number of times. For example,for _ in range(3):runs the block three times. The underscore is a convention for a variable you don't use. - Remember that
range()supports negative indices in slicing, but not in the arguments themselves. The start, stop, and step must be integers; they can be negative, but the logic must be consistent. - If you need a sequence of floats, use a while loop or
numpy.arange(). For example:i = 0.0; while i < 1.0: print(i); i += 0.1.
Troubleshooting
If your loop prints nothing: Check that your start and stop values are correct relative to the step. For a positive step, start must be less than stop. For a negative step, start must be greater than stop. If the condition is false, the range is empty.
If you get a TypeError about 'float' object cannot be interpreted as an integer: You passed a float to range. Convert to int using int() or use a different approach for decimal steps.
If you expected a list but see something like range(0, 5): That's normal. Wrap it with list() to get the actual numbers.
If your loop goes on forever: You likely used a while loop with a float increment that never exactly reaches the stop condition. Use an integer counter or compare with a tolerance.
If you get an IndexError when using range with len(): Make sure you are not modifying the list inside the loop, which changes its length. Iterate over a copy if needed.
Frequently Asked Questions
Does range() include the stop number?
No. The stop value is exclusive. range(5) gives 0,1,2,3,4.
Can I use range() with negative numbers?
Yes, as long as you provide appropriate start, stop, and step. For example, range(-5, 0) gives -5,-4,-3,-2,-1.
Is range() a generator?
No, it is a sequence type. It supports len(), indexing, and membership tests, and it is lazy (does not store all values).
How do I create a list of numbers from 1 to 10?
Use list(range(1, 11)). Remember stop is exclusive, so 11 is needed to include 10.
Can I use range() with a step of 0?
No, that raises a ValueError because step cannot be zero.
What is the fastest way to loop backwards?
Use range(10, 0, -1) to go from 10 down to 1. Or use reversed(range(10)) for 9 down to 0.