TOPIC 6: Python range ( )

1. Introduction

The built-in range() function is used to generate a sequence of numbers. It is commonly used with for loops when you want to repeat an action a specific number of times.

The sequence of numbers created by range() has its own data type called range.

Note: A range is immutable, which means it cannot be changed after it has been created.

Creating Ranges

The range() function can be called with one, two, or three arguments.

Syntax:

range(start, stop, step)

Where:

  • start: The number to begin from (optional).

  • stop: The number where the range stops (required).

  • step: The difference between each number (optional).

Calling range() with One Argument

If only one argument is provided, Python treats it as the stop value.

The starting value automatically becomes 0.

The stop value is not included in the sequence.

Example:

x = range(10)

print(list(x))

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Notice that 10 is not included.