Hi all,
I am wondering how to get the value a field frorm the first row without looping through all the rows?
Thanks
You still have to start a loop, but you can break out of it and kill the cursor at any time:
import arcpy fc = 'c:/data/base.gdb/features' # Open a cursor on some fields in a table with arcpy.da.SearchCursor(fc, ['OID@', 'SHAPE@AREA']) as cursor: for row in cursor: # Do something with the first row of data here break del cursor
Since the arcpy.da.SearchCursor is an iterable that returns one list per row of the table/cursor, the Python built-in next() function can be used to retrieve the next row, which would be the first row if the cursor was just created or reset.
import arcpy fc = 'c:/data/base.gdb/features' # Open a cursor on some fields in a table with arcpy.da.SearchCursor(fc, ['OID@', 'SHAPE@AREA']) as cursor: row = next(cursor) # Do something with the first row of data here del cursor
I try and that works
Thanks all of you
Or, something very similar, use the SearchCursor next method.
Cur = arcpy.da.SearchCursor(Feature, [Flds]) row = Cur.next()
Or to use a one-liner:
value = arcpy.da.SearchCursor(in_fc, ("YourFieldName",)).next()[0]
I try your code Xander and it work perfectly. That is really the easiest way to do it
Thanks for you all guys
If the cursor isn't going to be used once and disposed of, using a Python with statement ensures the cursor is reset for its next use. But then again, maybe having the cursor automatically reset isn't what someone wants. Just depends on the situation and need.
True, for now and in the ArcPy realm, calling the search cursor's next method will get the same result. I suggested using the built-in next method because of broader changes happening with Python outside of ArcPy. For Python 3 after PEP 3114 was approved, it meant the next() iterator method was going away. The Transition Plan for PEP 3114 covers two additional changes needed for moving to Python 3:
The built-in next function was introduced in Python 2.6 to smooth the transition. Since we know that Esri has made the leap to Python 3 with ArcGIS Pro, I suggested an approach using the built-in function. For now, Esri's implementation of the ArcPy Data Access (arcpy.da) module in ArcGIS Pro still includes cursors having explicit next() methods, but I argue the current ArcGIS Pro implementation isn't very pythonic since the explicit next() methods don't add any special functionality beyond simply iterating.
So to circle back, for the laymen, which approach would be the best to use?