The range()
function in Python is a powerful built-in function used to generate sequences of numbers. It is most commonly used in loops to iterate over a sequence of numbers, but it can also be applied in various contexts where a specific range of numbers is needed. The function returns an immutable sequence of numbers starting from a specified point (by default 0) and increments by a specified step (by default 1) until it reaches a defined endpoint.
range()
FunctionWhen range()
is used with a single argument, it generates a sequence starting from 0 and goes up to, but does not include, the specified value.
Output:
In this example, range(5)
generates the numbers 0 through 4.
With two arguments, range(start, stop)
generates a sequence starting from the first argument (start
) and ends before the second argument (stop
).
Output:
Here, range(2, 6)
generates numbers starting from 2 and ending at 5.
The range()
function can also take an optional third argument, which is the step value. This value defines the difference between each number in the sequence.
Output:
This example shows that range(1, 10, 2)
generates numbers starting from 1 and increments by 2 each time.
The range()
function also allows you to generate numbers in reverse by specifying a negative step value.
Output:
This code snippet shows range(10, 0, -2)
generating numbers starting from 10 and decrementing by 2.
range()
in PythonThe range()
function is frequently used in combination with len()
to loop through a list using indices.
Output:
You can easily generate a range of numbers and sum them using sum()
.
Output:
The range()
function in Python is essential for generating sequences of numbers efficiently. Whether you're using it to loop through a list, create custom ranges, or perform iterative calculations, it offers flexibility and power. Mastering range()
is crucial for effective iteration and looping in Python.