How to Create a Dynamic Range for Loop in Python?
Last Updated :
18 Dec, 2024
For L
oop 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 Variables
range()
function is the most common way to create a range for a loop in Python. It accepts start
, stop
, and step
parameters, all of which can be dynamically set using variables.
Python
start = 1
stop = 10
step = 2
# Loop through the range from 'start' to 'stop'
for i in range(start, stop, step):
print(i, end=" ")
Explanation:
range(start, stop, step)
generates numbers starting from start
(inclusive) to stop
(exclusive), incremented by step
.- By assigning values to
start
, stop
, and step
at runtime, we can define the range dynamically.
Let's explore some other methods to create a dynamic range for loop in Python.
Using a Generator Function
Generator functions offer a highly customizable and memory-efficient way to create dynamic ranges. These functions yield values one at a time, as needed by the loop.
Python
def dynamic_range(start, stop, step):
# Continue generating values as long as 'start' is less than 'stop'
while start < stop:
yield start
# Increment 'start' by 'step' for the next iteration
start += step
# Iterate through the values generated by the 'dynamic_range' function
for i in dynamic_range(1, 10, 2):
print(i, end=" ")
Explanation:
dynamic_range()
generator function yields numbers starting from start
and incremented by step
until stop
is reached.- Generators are lazy-loaded, meaning values are produced on-the-fly reducing memory usage.
Using numpy.arange()
NumPy
library provides the arange()
function which supports ranges with non-integer steps. This is particularly useful for scientific and mathematical applications.
Python
import numpy as np
start = 0.5
stop = 5.0
step = 0.5
# Iterate through the range using NumPy's arange function
for i in np.arange(start, stop, step):
print(i, end=" ")
Output0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5
Explanation:
numpy.arange(start, stop, step)
generates numbers starting from start
to stop - step
, incremented by step
.- This method supports floating-point numbers as well.
- The loop iterates through the sequence generated by
arange()
.
itertools.count()
function generates numbers indefinitely, making it suitable for open-ended loops. However, such loops must include a condition to terminate execution.
Python
from itertools import count
start = 3
step = 2
for i in count(start, step):
if i > 15: # Termination condition
break
print(i, end=" ")
Explanation:
itertools.count(start, step)
produces an infinite sequence of numbers starting from start
and incremented by step
.- The loop includes a
break
statement to terminate execution once a condition is met.
Dynamic ranges are particularly useful when the parameters are determined at runtime. By collecting start
, stop
, and step
values from user input, we can define a loop range interactively.
Python
start = int(input("Enter the start of the range: "))
stop = int(input("Enter the end of the range: "))
step = int(input("Enter the step size: "))
for i in range(start, stop, step):
print(i, end=" ")
Output:
OutputExplanation:
- The
input()
function gathers user-defined values for start
, stop
, and step
, and these values are converted into integers using int()
. - These dynamically provided values define the loop range at runtime.
Using a list
Lists can serve as dynamic ranges, especially when the sequence of values isn’t linear or follows a specific pattern. This approach allows iteration over predefined or dynamically generated elements.
Python
l = [10, 20, 30, 40]
for i in l:
print(i, end=" ")
Explanation:
- A list
'l'
holds the elements to iterate over which can be predefined or generated dynamically. - The
for
loop iterates through the elements in the list.
Similar Reads
How to Decrement a Python for Loop Pythonâs for loop is commonly used to iterate over sequences like lists, strings, and ranges. However, in many scenarios, we need the loop to count backward. Although Python doesn't have a built-in "decrementing for loop" like some other languages (e.g., for(int i = n; i >= 0; i--) in C++), there
2 min read
How to Access Index using for Loop - Python When iterating through a list, string, or array in Python, it's often useful to access both the element and its index at the same time. Python offers several simple ways to achieve this within a for loop. In this article, we'll explore different methods to access indices while looping over a sequenc
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
How to Create a List of N-Lists in Python In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
3 min read
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
Difference between for loop and while loop in Python In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if w
4 min read
Python - Loop Through a Range 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-poi
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
Different Ways to Create Numpy Arrays in Python Creating NumPy arrays is a fundamental aspect of working with numerical data in Python. NumPy provides various methods to create arrays efficiently, catering to different needs and scenarios. In this article, we will see how we can create NumPy arrays using different ways and methods. Ways to Create
3 min read
How to Build a basic Iterator in Python? Iterators are a fundamental concept in Python, allowing you to traverse through all the elements in a collection, such as lists or tuples. While Python provides built-in iterators, there are times when you might need to create your own custom iterator to handle more complex data structures or operat
4 min read