Python range() Function
The built-in
range()
function generates an immutable sequence of numbers. It is most commonly
used in loops when you need to repeat an action a specific number of times.
The object returned by
range() has
its own data type called
range.
Immutable means the sequence cannot be changed after it is created.
Creating a Range
The general syntax of the
range()
function is:
- start → starting value (inclusive, optional)
- stop → ending value (exclusive, required)
- step → difference between values (optional, default is 1)
Using range() with One Argument
When only one argument is provided, it represents the stop value. The sequence automatically starts from 0.
Using range() with Two Arguments
With two arguments, the first is the start, and the second is the stop.
Using range() with Three Arguments
The third argument defines the step size, which controls how much each value increases (or decreases).
Using range() in Loops
The
range()
function is widely used with
for loops.
Converting a Range to a List
A range object does not directly display all its values. To see the full sequence, convert it into a list.
Indexing and Slicing Ranges
Ranges behave like other sequences and support indexing and slicing.
Note:
- Indexing returns a single value
- Slicing returns a new range object
Checking Membership with in
You can check whether a value exists in a range using the
in keyword.
Finding the Length of a Range
The
len()
function returns how many numbers exist in a range.
