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:
range(start, stop, step)
• 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.
Output:
Using range() with Two Arguments
With two arguments, the first is the start, and the second is the stop.
Output:
Using range() with Three Arguments
The third argument defines the step size, which controls how much each value increases (or decreases).
Output:
Using range() in Loops
The range() function is widely used with for loops.
Output:
Count: 1
Count: 2
Count: 3
Count: 4
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.
Output:
[2, 3, 4, 5, 6]
[1, 5, 9]
Indexing and Slicing Ranges
Ranges behave like other sequences and support indexing and slicing.
Output:
[1, 2, 3, 4, 5]
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.
Output:
False
Finding the Length of a Range
The len() function returns how many numbers exist in a range.
