When programming in Python, we often encounter situations where we want to run a for loop “only 5 times” or get “consecutive numbers from 10 to 20”. This is where the range() function comes in.
range() is not a list itself, but an object designed to generate a “sequence of numbers” based on specified rules. This article explains the basic usage of range() in three patterns. You can check the contents of a range() object by wrapping it with the list() function.
1. range(stop) – One Argument (Starts from 0)
When you specify only one argument (stop), the sequence starts from 0 and ends just before stop (stop - 1).
# Sequence from 0 to 4 (stops before 5)
seq1 = range(5)
print(f"range(5) -> {list(seq1)}")
Output:
range(5) -> [0, 1, 2, 3, 4]
2. range(start, stop) – Two Arguments (Start and Stop)
When you specify two arguments (start, stop), the sequence starts from start and ends just before stop (stop - 1).
# Sequence from 100 to 102 (stops before 103)
seq2 = range(100, 103)
print(f"range(100, 103) -> {list(seq2)}")
Output:
range(100, 103) -> [100, 101, 102]
3. range(start, stop, step) – Three Arguments (With Step)
When you specify three arguments (start, stop, step), the sequence generates numbers from start up to just before stop, incrementing by step.
# From 10 to just before 31, increasing by 10
seq3 = range(10, 31, 10)
print(f"range(10, 31, 10) -> {list(seq3)}")
Output:
range(10, 31, 10) -> [10, 20, 30]
4. Negative Value for step (Reverse Order)
By specifying a negative value for step, you can generate a sequence that decreases from start to stop (reverse order). In this case, start must be larger than stop.
# Decrease by 1 from 3 to 1 (stops before 0)
seq4 = range(3, 0, -1)
print(f"range(3, 0, -1) -> {list(seq4)}")
Output:
range(3, 0, -1) -> [3, 2, 1]
Note that the stop value (0 in this case) is not included.
Using in for Loops
The most common way to use range() is directly in a for loop, without converting it with list(). This allows you to execute repetitive tasks efficiently without creating huge lists in memory.
print("--- Loop Start ---")
# Loop 3 times: 0, 1, 2
for i in range(3):
print(f"Current value of i: {i}")
print("--- Loop End ---")
Output:
--- Loop Start ---
Current value of i: 0
Current value of i: 1
Current value of i: 2
--- Loop End ---
Summary
range(stop): From 0 tostop - 1.range(start, stop): Fromstarttostop - 1.range(start, stop, step): Fromstarttostop - 1, skipping bystep.- You can create a reverse sequence by specifying a negative value for
step. - It is most commonly used in combination with
forloops.
