How to create a for loop with dynamic range?

I repeat the list. An item can be added to this list during iteration. So the problem is that the loop only repeats through the original length of this list.

My code is:

i = 1 for p in srcPts[1:]: # skip the first item. pt1 = srcPts[i - 1]["Point"] pt2 = p["Point"] d = MathUtils.distance(pt1, pt2) if (D + d) >= I: qx = pt1.X + ((I - D) / d) * (pt2.X - pt1.X) qy = pt1.Y + ((I - D) / d) * (pt2.Y - pt1.Y) q = Point(float(qx), float(qy)) # Append new point q. dstPts.append(q) # Insert 'q' at position i in points st 'q' will be the next i. srcPts.insert(i, {"Point": q}) D = 0.0 else: D += d i += 1 

I tried using for i in range(1, len(srcPts)): but again the range remains the same even after more items are added to the list.

+4
source share
3 answers

The problem is that len(srcPts) evaluated only once when you pass it as an argument to the range generator. Therefore, you need to have a termination condition that reevaluates the current srcPts length during each iteration. There are many ways to do this, for example:

 while i < len(srcPts): .... 
+4
source

In this case, you need to use the while :

 i = 1 while i < len(srcPts): # ... i += 1 

A for loop creates an iterator for your list once. And once created, this iterator does not know that you have changed the list in a loop. The while option shown here recalculates the length each time instead.

+8
source

In line:

 for p in srcPts[1:]: # skip the first item. 

slicing creates a new copy of scrPtrs, therefore a fixed size.

Disclaimer: it is not correct to modify a list that is an iterator, but this works ...

Creating an iterator over a list prevents copying and allows you to add and paste elements:

 L = [1,2,2,3,4,5,2,2,6] it = iter(L) next(it) # skip the first item for i,p in enumerate(it,1): if p == 2: L.insert(i+1,7) # insert a 7 as the next item after each 2 print(p) 

Output:

 2 7 2 7 3 4 5 2 7 2 7 6 
+1
source

All Articles