Python Forum
repeating a range - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: repeating a range (/thread-37922.html)



repeating a range - Skaperen - Aug-09-2022

a function gets a range as a parameter. this function needs to go through this range many times. the number of times varies depending on other parameters. can iter() replicate the range for me each time like for x in iter(the_range):?


RE: repeating a range - Yoriz - Aug-09-2022

As far as I can tell I turned your description into code.
def a_function(the_range, many_times):
    for _ in range(many_times):
        for x in iter(the_range):
            print(x)


a_function(range(3), 3)
Output:
0 1 2 0 1 2 0 1 2



RE: repeating a range - Gribouillis - Aug-09-2022

(Aug-09-2022, 07:03 PM)Yoriz Wrote: As far as I can tell I turned your description into code.
When you have
for x in iter(spam):
    ...
you can as well remove iter() because the for loop calls iter()
for x in spam:
    ...



RE: repeating a range - Skaperen - Aug-09-2022

that i did not know. now i need to scan all my code for that case.


RE: repeating a range - DeaD_EyE - Aug-10-2022

def loop(range_object, repeats=4):
    for _ in range(repeats):
        for x in range_object:
            print(x)


my_range = range(10, -1, -1)
loop(my_range, repeats=4)
The range object is only once instantiated and reused 4 times.

With itertools.repeat:
from itertools import repeat


my_range = range(10, -1, -1)
for range_object in repeat(my_range, times=4):
    for value in range_object:
        print(value)
If times is not given, then repeat repeats infinite.


RE: repeating a range - Skaperen - Aug-10-2022

the case i have is a caller creates the range object and passes it and other parameters to a function. the function can accept any iterator in place of the range. that function iterates that iterator repeatedly until a condition is met. the function may be designed as a generator in which the yield statement may be inside or outside the body of that iteration. it is not at simple as a number being provided or determined then repeating the iteration that many times. however, a design around a number may be a simple way to test iterator object management.

the code for this has not been written. all the design ideas in a project had this need and i was trying to work around that need and could not. but, since iter() can do this, all the function should need to do is hang on to the original iterator/range and make transient copies with iter() and use those results each time.

it might be convenient to have a quick means to get a count of the number of times an iterator should step through its range without having to literally run it. for range(), this can be calculated. for other things, such as an iterator reading a network connection, it may be impossible.