
Python range() Function: Complete Guide with Examples
The Python range() function is a built-in method used to generate a sequence of numbers. It’s commonly utilized in for loops to control iteration. Introduced in Python 3.x, range() replaced the older xrange().
Syntax of Python range()
Python range() Function
python
range(start, stop, step)
- start (optional): The starting value. Defaults to 0 if not provided.
- stop (required): The ending value. The range will stop one value before this number.
- step (optional): The increment value. Defaults to 1 if not provided.
Examples of Using Python range()
1. Basic range() Example
python
for i in range(5):
print(i, end=” “)
Output: 0 1 2 3 4
2. Using start and stop Parameters
python
for i in range(3, 10):
print(i, end=” “)
Output: 3 4 5 6 7 8 9
3. Using step Parameter
python
for i in range(3, 10, 2):
print(i, end=” “)
Output: 3 5 7 9
4. Decrementing Using Negative Step
python
for i in range(15, 5, -1):
print(i, end=” “)
Output: 15 14 13 12 11 10 9 8 7 6
5. Using range() in Lists
python
print(list(range(10)))
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6. Accessing Range Elements via Index
python
print(range(5)[0]) # First Element
print(range(5)[-1]) # Last Element
Output:
0
4
Python range() Function Important Notes
- The range() function only supports integer values. Attempting to use floats will result in a TypeError.
- For floating-point sequences, use NumPy’s arange().
Using NumPy arange() for Floating-Point Sequences
python
import numpy as np
for i in np.arange(0.5, 1.5, 0.2):
print(i, end=” “)
Output: 0.5 0.7 0.9 1.1 1.3
Merging Two Ranges Using itertools
python
from itertools import chain
for i in chain(range(5), range(10, 15)):
print(i, end=” “)
Output: 0 1 2 3 4 10 11 12 13 14
Key Differences Between range() and xrange()
- range() returns a list (in Python 3.x).
- xrange() returns a generator object (used in Python 2.x).
- range() consumes more memory, while xrange() is memory efficient.