range() Function
Understanding range()
The range() function in Python generates a sequence of numbers. It's commonly used for iterating over a specific number of times using for loops.
Syntax
Python
range(stop)
range(start, stop, step)
Use code with caution.
Parameters
- stop: Required. The sequence ends at stop - 1.
- start: Optional. The sequence starts at start. Default is 0.
- step: Optional. The difference between each number in the sequence. Default is 1.
Examples
Python
# Basic usage
numbers = range(5)
print(list(numbers)) # Output: [0, 1, 2, 3, 4]
# Starting from 2, ending at 10, with a step of 2
numbers = range(2, 10, 2)
print(list(numbers)) # Output: [2, 4, 6, 8]
# Counting backwards
numbers = range(10, 0, -2)
print(list(numbers)) # Output: [10, 8, 6, 4, 2]
Use code with caution.
Important Points
- range() returns an immutable sequence object, not a list. To convert it to a list, use list(range(...)).
- The stop value is exclusive, meaning it's not included in the generated sequence.
- The step can be negative to create a decreasing sequence.
Common Use Cases
- Iterating over a sequence of numbers in a for loop.
- Creating lists of numbers.
- Generating indices for accessing elements in other sequences.
Example with a for loop
Python
for i in range(5):
print(i)
Use code with caution.
In essence, range() is a versatile function for creating sequences of numbers, which is often used in conjunction with loops for repetitive tasks.