Python range()
Function
The range() function in Python is used to generate a sequence of numbers. It's commonly used in for
loops to repeat a block of code a specific number of times.
Syntax
range(stop)
range(start, stop)
range(start, stop, step)
Parameters:
start
(optional) – The starting number of the sequence. Defaults to 0.stop
– The number at which to stop (not included).step
(optional) – The difference between each number in the sequence. Defaults to 1.
Returns:
An immutable sequence type of numbers.
Example 1: Using range(stop)
for i in range(5):
print(i)
0
1
2
3
4
Example 2: Using range(start, stop)
for i in range(2, 6):
print(i)
2
3
4
5
Example 3: Using range(start, stop, step)
for i in range(1, 10, 2):
print(i)
1
3
5
7
9
Example 4: Reversed Sequence with Negative Step
for i in range(5, 0, -1):
print(i)
5
4
3
2
1
Use Cases
- Looping over a fixed number of times
- Generating indices for list access
- Iterating in reverse
- Creating sequences for algorithms
Convert to List (for Viewing)
print(list(range(1, 6)))
[1, 2, 3, 4, 5]
Using list()
helps you visualize the numbers generated by range()
.
Common Mistakes
- Forgetting that
stop
is exclusive (not included) - Using a step of 0 will raise a
ValueError
- Assuming
range()
returns a list – it returns a special range object
Interview Tip
range()
is often used in loop-based questions. Practice customizing start, stop, and step to write optimized code.
Summary
range()
generates numbers fromstart
tostop - 1
- It’s memory-efficient and commonly used in loops
- Convert to
list()
if you want to view or print the sequence
Practice Problem
Print all even numbers between 10 and 30 using range()
.
for i in range(10, 31, 2):
print(i)
10
12
14
16
18
20
22
24
26
28
30