Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dynamic range for loop?

I aim to create a dynamic range of a python loop. I know once the end range is computed only once, when it is passed as an argument to the range generator. However, this an example:

i = 1
for i in range(1,i,1):
    print i
    i = i +1

it is obvious that with i=1 the loop is skipped. But I want somehow that this range is dynamically changing according to i parameter.

This is my case where I want to use a dynamic range:

  1. I calculate the capacity of a link
  2. I calculate the bandwidth on that link
  3. I do a loop with increasing of traffic sent in which should be equal to the capacity, I call it overload value.
  4. The increasing is of range starts from 1 to the overload value.

This overload value is being calculated every time in each iteration, and it updates the range. If say theoretically the overload value is 20, then the range goes until 20.

This is my code:

capacity = Router_1.get_tunnel_capacity()
tunnel_bandwidth = Router_1.check_bandwidth_overload()
    if tunnel_bandwidth <= capacity:
        for bandwidth in range(1, range_end, 1):
            os.system('iperf -c ' + server_address + ' -u -p 50001 -b ' + str(bandwidth) + 'M -i 1')
tunnel_bandwidth = Router_1.check_bandwidth_overload()
if tunnel_bandwidth <= capacity:
   # update the range_end according to tunnel_bandwidth

range_end is the dynamic value of the range. Is there anyway to make it dynamic?

like image 602
Tim Luka Avatar asked Apr 25 '26 01:04

Tim Luka


2 Answers

Use a while loop instead of a for loop. This is a really basic example:

z = 0
range = 10
while z < range:
    print(z)
    if z == 9:
        range = 20
    z += 1
like image 133
Rob Kwasowski Avatar answered Apr 26 '26 17:04

Rob Kwasowski


The while-loop answer given by Rob is likely to be the best solution as the range() function in Python 3 returns a lazy sequence object and not a list.

However, in Python 2 when you call range() in a for loop, it creates a list. You can save that list and then mutate it.

Something like this:

count = 10
r = range(count)
for i in r:
    newcount = 7
    del r[newcount:]

I am not too sure how would it work for increasing the size but you get the idea.

like image 30
Shayan Avatar answered Apr 26 '26 17:04

Shayan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!