range()
in Python – Explained with Examples
The range()
function in Python is used to generate a sequence of numbers. It's commonly used in loops and list comprehensions.
Basic Syntax:
range(start, stop, step)
start
(optional): Starting number of the sequence (default is 0)
stop
(required): Generate numbers up to, but not including, this number
step
(optional): Difference between each number in the sequence (default is 1)
Examples
1. Using range(stop)
for i in range(5):
print(i)
Output:
0
1
2
3
4
- Starts from 0
- Stops at 5 (exclusive)
- Step is 1 (default)
2. Using range(start, stop)
for i in range(2, 6):
print(i)
Output:
2
3
4
5
3. Using range(start, stop, step)
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
- Starts at 1
- Ends before 10
- Increments by 2
4. Reverse Range
for i in range(10, 0, -1):
print(i)
Output:
10
9
8
...
1
- Generates numbers in reverse using a negative step
5. Convert range
to List or Tuple
print(list(range(5))) # [0, 1, 2, 3, 4]
print(tuple(range(3, 7))) # (3, 4, 5, 6)
6. Empty Range
print(list(range(5, 2))) # []
- Since 5 is greater than 2 and no step is provided, it results in an empty sequence.
Use Cases
- Loops: Commonly used in
for
loops
- Indexing: Iterating over list indices
- List comprehension: Efficient sequence creation
Summary Table
Syntax |
Description |
range(5) |
0 to 4 |
range(2, 6) |
2 to 5 |
range(1, 10, 2) |
1, 3, 5, 7, 9 |
range(10, 0, -1) |
10 to 1 in reverse |
list(range(3)) |
Convert to list: [0, 1, 2] |