Python - Loop Through a Range
Last Updated :
23 Dec, 2024
Looping through a range is an important operation in Python. In this article, we will explore the different ways to loop through a range in Python, demonstrating how we customize start, end, and step values, as well as alternative methods for more advanced use cases like looping through floating-point ranges or infinite sequences.
Example of Using range()
The most simple way to loop through a range in Python is by using the range()
function in a for
loop. By default, the range()
function generates numbers starting from 0
up to, but not including, the specified endpoint.
Python
# Loop from 0 to 4
for i in range(5):
print(i, end=" ")
Explanation:
- Here only one argument is provided so the range begins at
0
. - The range ends at
n-1 i.e. 4
, where n
is the argument provided.
Let's see some more methods and see how we can loop through a range in Python.
Using Start and Step Value in range()
In Python, we can loop through a range using the start parameter by leveraging the range() function. The range() function can take up to three parameters: start, stop, and step. Here’s the general syntax for using the start parameter in range():
range(start, stop, step)
- start: The value at which the range starts (inclusive).
- stop: The value at which the range stops (exclusive).
- step: The increment or decrement for each iteration (default is 1).
Example:
Python
# Loop with a step value of 2
for i in range(0, 10, 2):
print(i, end=" ")
Explanation:
- The step value(2) determines how much the range increments after each iteration.
- It supports both positive and negative step values for ascending or descending loops.
Note: Python also allows looping in reverse order by setting a negative step value in the range()
function.
#Loop from 10 to 1 in reverse
for i in range(10, 0, -1):
print(i, end=" ") # Output: 10 9 8 7 6 5 4 3 2 1
Using enumerate()
and range()
The enumerate()
function, when combined with range()
, provides both the index and the value during iteration.
Python
# Loop with index and value
for idx, val in enumerate(range(5, 10)):
print(f"Index: {idx}, Value: {val}")
OutputIndex: 0, Value: 5
Index: 1, Value: 6
Index: 2, Value: 7
Index: 3, Value: 8
Index: 4, Value: 9
Explanation:
enumerate()
returns a tuple containing the index and the corresponding value in the range.- It works seamlessly with ranges of any size.
Looping Through Floating-Point Ranges
Since the range()
function only supports integers, creating a range of floating-point numbers requires external libraries or custom solutions. Here we will use numpy.arrange().
Python
import numpy as np
# Loop through floating-point numbers
for i in np.arange(0.5, 2.5, 0.5):
print(i, end=" ")
Explanation:
Here, NumPy
allows iteration over fractional ranges.- It Supports precise step values for scientific or mathematical applications.
The itertools.count()
function generates an infinite sequence of numbers, starting from a given value and stepping by a defined amount. It is suitable for dynamic or unpredictable iteration lengths, such as streaming data.
Python
from itertools import count
# Infinite range with manual termination
for i in count(1, 3):
if i > 10:
break
print(i, end=" ")
Explanation:
- Here, it automatically continues until a stopping condition is provided.
- It supports both positive and negative step values.
Similar Reads
range() to a list in Python In Python, the range() function is used to generate a sequence of numbers. However, it produces a range object, which is an iterable but not a list. If we need to manipulate or access the numbers as a list, we must explicitly convert the range object into a list. For example, given range(1, 5), we m
2 min read
Python - Iterating through a range of dates In this article, we will discuss how to iterate DateTime through a range of dates. Using loop and timedelta to Iterate through a range of dates Timedelta is used to get the dates and loop is to iterate the date from the start date to end date Syntax: delta = datetime.timedelta(days=1) Example: Pytho
2 min read
JS Equivalent to Python Range In Python, the range() function is used to generate a sequence of numbers, commonly for iteration in loops. JavaScript, however, doesnât have a built-in range() function, but there are various ways to achieve similar functionality. In this article, we will explore how to replicate the behavior of Py
5 min read
range() vs xrange() in Python The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(
4 min read
Python range() Method range() function in Python is used to generate a sequence of numbers. It is widely used in loops or when creating sequences for iteration. Letâs look at a simple example of the range() method.Python# Generate a sequence of numbers from 0 to 4 for i in range(5): print(i) Output0 1 2 3 4 Explanation:T
3 min read
Python | range() does not return an iterator range() : Python range function generates a list of numbers which are generally used in many situation for iteration as in for loop or in many other cases. In python range objects are not iterators. range is a class of a list of immutable objects. The iteration behavior of range is similar to iterat
2 min read
How to Create a Dynamic Range for Loop in Python? For Loop is widely used to iterate over sequences in Python. However, there are situations where the range or sequence of the loop needs to be dynamic, and determined at runtime. In this article, we will explore various methods to achieve dynamic range for loops.Using range() with Variablesrange() f
4 min read
Python | pandas.date_range() method Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. pandas.date_range() is one of the general functions in Pandas which is used to return
4 min read
Python While Loop Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.In this example, the condition for while will be True as long as the counter variable (count) i
5 min read
Python range() function The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops.ExampleIn the given example, we are printing the number from 0 to 4.Pythonfor i in range(5): print(i, end=" ") print()Output:0 1
7 min read