I'm trying to extract a list of unique values in two fields in a shapefile. I think I am misunderstanding how the search cursor works, because I get the same error on which ever variable (x or y) I put second.

I'm following the answer here, and it works for just one field, but not 2+


with arcpy.da.SearchCursor(myshp, ['myid', 'myname']) as cursor:
    x = sorted({row[0] for row in cursor})
    y = sorted({row[1] for row in cursor})


y = sorted({row[1] for row in cursor})
IndexError: list index out of range

2 Answers 2


You can use a generator expression for this. For example:

import arcpy

fc = r'C:\path\to\geodatabase.gdb\featureclass'

unique_list1 = set(row[0] for row in arcpy.da.SearchCursor(fc, 'myid'))
unique_list2 = set(row[0] for row in arcpy.da.SearchCursor(fc, 'myname'))

Although an existing answer works, it will not perform well for large feature classes and tables or when looking for unique values in many fields. Using defaultdict - collections - Container datatypes - Python 3.x documentation, one can loop through a cursor once and retrieve unique values for an arbitrary number of fields:

import arcpy
import collections

table =  # path to feature class or table, or name of layer or table view
fields = # list of field names to gather unique values

unique_values = collections.defaultdict(set)
with arcpy.da.SearchCursor(table, fields) as cur:
    for row in cur:
        for i, value in enumerate(row):

for k, v in unique_values.items():
    print(*sorted(i for i in v if i is not None), sep="\n")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.