
Table of Contents(目次)
Mastering the range() Function
In this lecture, we’ll take a closer look at the range() function, which is often used together with the for
loop.
Basics of the range() Function
Basically, range()
returns a sequence of numbers starting from 0
when you pass a single integer as an argument. When you provide multiple arguments, you can control the range of numbers generated—similar to how list slicing works.
Arguments and Returned Integers
range(n)
: Returns integers from0
up ton - 1
.- If
n
is a negative value or 0, no numbers are returned, and thefor
loop terminates without running even once. - If
n
is greater than or equal to 1, the loop will iterate n times.range(3)
:0 → 1 → 2
- If
range(n, m)
: Returns integers fromn
up tom - 1
.- Pass arguments such that
n < m
.range(1, 5)
:1 → 2 → 3 → 4
- If
n > m
, nothing is returned.range(5, 1)
: # returns nothing
- If
n < m
, you can also use negative values.range(-5, 0)
:-5 → -4 → -3 → -2 → -1
- Pass arguments such that
range(n, m, step)
: When you specify thestep
value, it extracts elements fromrange(n, m)
at intervals ofstep
.- Unlike list slicing, both
n
andm
must be explicitly defined.-
range(1, 20, 5)
:1 → 6 → 11 → 16
-
- You can also specify a negative value for
step
.- When a negative value is used, numbers are generated in reverse order. In this case,
n
andm
must satisfy the conditionn > m
. range(5, 1, -1)
:5 → 4 → 3 → 2
- When a negative value is used, numbers are generated in reverse order. In this case,
- Unlike list slicing, both
1. Basics of range(n)
range(n)
generates integers sequentially from 0
to n - 1
.
for i in range(5):
print(i)
Example Output:
0
1
2
3
4
2. Using range(n, m)
range(n, m)
generates integers from n
to m - 1
. Unlike list slicing, n
cannot be omitted.
for i in range(2, 6):
print(i)
Example Output:
2
3
4
5
3. Specifying Steps with range(n, m, step)
range(n, m, step)
generates integers from n
to m - 1
in increments of step
. The step
value can be either positive or negative.
for i in range(1, 10, 2):
print(i)
Example Output:
1
3
5
7
9
When a negative step
is specified, numbers are generated in reverse order.
for i in range(5, 0, -1):
print(i)
Example Output:
5
4
3
2
1