Skip to content

Instantly share code, notes, and snippets.

@bixb0012
Last active July 31, 2019 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bixb0012/e0db4761b82a679761ac1d681155ecbe to your computer and use it in GitHub Desktop.
Save bixb0012/e0db4761b82a679761ac1d681155ecbe to your computer and use it in GitHub Desktop.
ArcPy (Pro): Look-Ahead Cursor
#!python3
# Reference: 1) https://pro.arcgis.com/en/pro-app/arcpy/data-access/searchcursor-class.htm
# 2) https://pro.arcgis.com/en/pro-app/arcpy/data-access/updatecursor-class.htm
# 3) https://docs.python.org/3/library/itertools.html
import arcpy
from itertools import chain, zip_longest, tee
fc = # Path to feature class or name of feature layer
flds = # Fields to include in cursor
# Example 1a: Read-only, look-ahead using search cursor & itertools chain, izip, tee
with arcpy.da.SearchCursor(fc, flds) as cur:
n, n1 = tee(cur)
n1 = chain(n1, (next(n1),))
for n_row, n_1row in zip(n, n1):
print(n_row, n_1row)
# Example 1b: Read-only, look-ahead using search cursor & itertools izip_longest, tee
with arcpy.da.SearchCursor(fc, flds) as cur:
n, n1 = tee(cur)
filler_row = next(n1)
for n_row, n_1row in zip_longest(n, n1, fillvalue=filler_row):
print(n_row, n_1row)
# Example 2: Look-ahead using search cursor and nested update cursor
# & itertools izip_longest
with arcpy.da.SearchCursor(fc, flds) as n1_cur:
with arcpy.da.UpdateCursor(fc, flds) as n_cur:
filler_row = next(n1_cur)
for n_row, n1_row in zip_longest(n_cur, n1_cur, fillvalue=filler_row):
print(n_row, n1_row)
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment