Borealis Borealis - 4 months ago 19
Python Question

How to limit for loop iterations within cursor?

I am using a

for
loop within a SearchCursor to iterate through features in a featureclass.

import arcpy

fc = r'C:\path\to\featureclass'

with arcpy.da.SearchCursor(fc, ["fieldA", "FieldB", "FieldC"]) as cursor:
for row in cursor:
# Do something...


I am currently troubleshooting the script and need to find a way to limit the iterations to, say, 5 rather than 3500 as it is currently configured. I know the most basic way to limit the number of iterations in a
for
loop is as follows:

numbers = [1,2,3,4,5]

for i in numbers[0:2]
print i


However, this approach does not work when iterating over a cursor object. What method can I use to limit the number of iterations of a
for
loop within a cursor object wrapped in a
with
statement?

Answer

Add a counter and a logical statement to limit the number of iterations. For example:

import arcpy

fc = r'C:\path\to\featureclass'

count = 1 # Start a counter

with arcpy.da.SearchCursor(fc, ["fieldA", "FieldB", "FieldC"]) as cursor:
    for row in cursor:
        # Do something...
        if count >= 2:
            print "Processing stopped because iterations >= 2"
            sys.exit()

        count += 1