Range
range() in Python
The range() function in Python is used to generate a sequence of numbers. It's commonly utilized in for loops to iterate a fixed number of times efficiently.
Forms of the range() Function
The range() function can be used in three forms:
-
range(stop)
Generates numbers from 0 up to, but not including, stop. -
range(start, stop)
Generates numbers from start up to, but not including, stop. -
range(start, stop, step)
Generates numbers from start up to, but not including, stop, incrementing by step (which can be positive or negative).
1. range(stop)
When using a single argument, the sequence starts at 0 and ends at stop - 1.
Example:
Output:
2. range(start, stop)
When two arguments are given, the sequence starts from start and ends at stop - 1.
Example:
Output:
3. range(start, stop, step)
With three arguments, range() defines the start, end, and step between values.
Example:
Output:
Additional Examples
Example 1: Range with Negative Step
Output:
Example 2: Negative Step with Different Interval
Output: