2

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?

2
  • 1. Also use a variable for the end argument? 2. Changing i inside the loop will not have the effect you expect Commented Jul 11, 2019 at 10:36
  • Use a while loop instead. Commented Jul 11, 2019 at 10:38

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.