Understanding the range() Function
The range()
function in Python is a built-in function that generates a sequence of numbers. It is commonly used in for
loops to iterate over a specific range of values. The range()
function can be used in various ways to create different sequences of numbers.
Syntax of the range() Function
The range()
function can be used with one, two, or three arguments:
range(stop)
: This creates a sequence of numbers starting from 0 and ending at stop - 1
.
range(start, stop)
: This creates a sequence of numbers starting from start
and ending at stop - 1
.
range(start, stop, step)
: This creates a sequence of numbers starting from start
, ending at stop - 1
, and incrementing/decrementing by step
.
## Example usage of range() function
print(list(range(5))) ## Output: [0, 1, 2, 3, 4]
print(list(range(2, 8))) ## Output: [2, 3, 4, 5, 6, 7]
print(list(range(1, 10, 2))) ## Output: [1, 3, 5, 7, 9]
Understanding the Behavior of range()
The range()
function generates a sequence of numbers, but it does not actually create a list of those numbers. Instead, it returns a range
object, which is an immutable sequence type. To use the numbers generated by range()
, you need to convert the range
object to a list or iterate over it directly.
## Understanding the range() function
print(type(range(5))) ## Output: <class 'range'>
print(list(range(5))) ## Output: [0, 1, 2, 3, 4]
The range()
function is memory-efficient because it only stores the start, stop, and step values, rather than the entire sequence of numbers. This makes it useful for working with large ranges of numbers without consuming a lot of memory.