sec03 - Mastering the range() Function in Python: From Basics to Practice
スポンサーリンク

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 from 0 up to n - 1.
    • If n is a negative value or 0, no numbers are returned, and the for 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
  • range(n, m): Returns integers from n up to m - 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
  • range(n, m, step): When you specify the step value, it extracts elements from range(n, m) at intervals of step.
    • Unlike list slicing, both n and m 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 and m must satisfy the condition n > m.
      • range(5, 1, -1): 5 → 4 → 3 → 2

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
スポンサーリンク