Tim Luka
Tim Luka

Reputation: 481

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?

Upvotes: 2

Views: 15022

Answers (3)

Davide Fazio
Davide Fazio

Reputation: 29

If you want to change the range_end in the for loop you can't do this, try to use a while loop.

Upvotes: 0

Shayan
Shayan

Reputation: 2471

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.

Upvotes: 2

Rob Kwasowski
Rob Kwasowski

Reputation: 2780

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

Upvotes: 7

Related Questions