Hello everyone,
Is there a way to count records returned by a arcpy.da.SearchCursor?
This is how I am doing the count
# Initialize
count = 0
srcToday = None
with arcpy.da.SearchCursor(FeatureClass, fieldnames, whereClause) as srcToday:
for rowToday in srcToday:
count = count + 1
if count == 0:
……
You can read the cursor with a list comprehension, like so:
featureList = [row[0] for row in arcpy.da.SearchCursor(FeatureClass, fieldnames, whereClause) ]
print(len(featureList))
Is it faster than:
for rowToday in srcToday:
count = count + 1
Depending on how many records you have, probably not. Search cursors are not the fastest things around. What really helps speed them up is the 'where clause'. That way it only 'hits' those records that meet the criteria.
If you need to count how many records result from a specific criteria, and not process those records, then Make Feature Layer and Get Count is the best.
If you really want to use native Python, instead of geoprocessing tools, then most of the methods will all be similar in terms of performance because iterating through the entire cursor takes the same amount of time regardless of how you are counting the records.
For me, the most Pythonic way would be to leverage Python built-in functions. For example,
with arcpy.da.SearchCursor(FeatureClass, fieldnames, whereClause) as srcToday:
count = sum(1 for row in srcToday)
Question, do you want to call how many records are in the cursor or whether there are any records? If the latter, some techniques are much more efficient than others.
Hi Joshua,
I am only interested in knowing it there are any records, not the number of records.
Could you please explain the other techniques.
Thanks
Since I am not sure what your code looks like before or after this point, I can't say whether this is the "best" overall approach. Focusing only on the question of whether a cursor has any items/rows, Python's built-in any function is the most Pythonic both in terms of form and function.
if any(arcpy.da.SearchCursor(FeatureClass, fieldnames, whereClause)):
....
The above is checking for records, insert a not if you are interested in checking for no records. What is great about any, beyond the semantic straightforwardness of using 'any' to check for any records, is that it also short-circuits and exits at the first True value. This comes in especially handy when the iterable is very long, and looping through it would take time.