In Python, the range function can take three arguments: start, stop, and step. The syntax is as follows:
range(start, stop, step)
Explanation of Each Argument
-
start:- The value at which the sequence begins (inclusive).
- Default is
0if not specified.
-
stop:- The value at which the sequence ends (exclusive).
- This argument is required.
-
step:- The difference between each consecutive number in the sequence.
- Default is
1if not specified. - Can be negative to generate a decreasing sequence.
Examples
-
Basic Example:
print(list(range(1, 10, 2))) # Output: [1, 3, 5, 7, 9]- Starts at
1, ends before10, and increments by2.
- Starts at
-
Negative Step:
print(list(range(10, 0, -2))) # Output: [10, 8, 6, 4, 2]- Starts at
10, ends before0, and decrements by2.
- Starts at
-
Default Step:
print(list(range(5))) # Output: [0, 1, 2, 3, 4]- Starts at
0, ends before5, with a default step of1.
- Starts at
Summary
- The three-argument form of
rangeallows for more control over the sequence of numbers generated, enabling you to specify where to start, where to stop, and how to increment or decrement the values.
If you have any further questions or need clarification, feel free to ask!
