What is the use of the "range" function in Python?
Table of Contants
Introduction
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.
How to Use the range() Function
1. Basic Usage: One Argument
When 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.
2. Specifying a Start and Stop: Two Arguments
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.
3. Using a Step Value: Three Arguments
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.
4. Using Negative Step Values
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.
Practical Examples of range() in Python
Example : Looping Through a List by Index
The range() function is frequently used in combination with len() to loop through a list using indices.
Output:
Example : Summing Numbers in a Range
You can easily generate a range of numbers and sum them using sum().
Output:
Conclusion
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.