How to use the range function in a loop in Python?
Published on Aug. 22, 2023, 12:18 p.m.
To use the range()
function in a loop in Python, you can simply use the for
loop syntax and specify the range()
function as the list of values to iterate over. Here’s an example:
for i in range(5):
print(i)
This will loop through the values 0
, 1
, 2
, 3
, and 4
, and print each of them on a separate line.
You can also specify a starting value for the range, as well as a range increment. For example:
for i in range(1, 10, 2):
print(i)
This will loop through the values 1
, 3
, 5
, 7
, and 9
, and print each of them on a separate line.
Note that the range function returns a range object in Python 3, which is an iterable sequence of numbers. If you want to get a list of the values, you can use the list()
function to convert the range object to a list.