In this article, you will learn how to use the Python range() function.
Python range() Function
The range() function in Python generates a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
The numbers generated by range() are used as indices for iterating over a sequence, such as lists, tuples, and strings.
The function is an efficient way to generate a sequence of numbers as it generates the numbers on-the-fly, rather than storing them in memory as a list.
The basic syntax for range() is as follows:
stop is the upper bound of the sequence, and is not included in the sequence.
This generates a sequence of numbers from 0 to
The function works with any integer value, including negative numbers.
The following is an example of how to use the range() function to generate a sequence of numbers from 0 to 9:
for i in range(10): print(i)
You can also specify the start and step of the sequence by using the following syntax:
range(start, stop, step)
start is the first number in the sequence, defaulting to 0 if not specified.
step is the difference between each number in the sequence, defaulting to 1 if not specified.
The function can also be used to generate sequences of numbers with a step of -1, allowing for generation of decreasing sequences.
For example, to generate a sequence of even numbers from 0 to 10, you can use the following code:
for i in range(0, 11, 2): print(i)
Note that the range() function generates a sequence of numbers, and does not return a list. To generate a list, you need to use the list() function, like so:
my_list = list(range(10))