[GIS] Passing Python List into Layer Definition Query

definition-querypython

I am trying to cursor search through items in a field in a feature class. I then append them to a list called 'distList'. I want to pass the list into layers definition query as follows:

"Field1" in distList

or in long hand, it would look like this:

"Field1" in ('ds(c1)', 'ds(b1)', 'ds(c2)', 'ds(g1)')

The list looks like this:

['ds(c1)', 'ds(b1)', 'ds(c2)', 'ds(g1)']

The problem I am having is, the definition query above doesn't like to look 'in' a python list. It doesn't recognize the square brackets. It prefers round brackets, so I thought about using a tuple. The problem I am facing is I don't know how to build a tuple after cursor searching the items from the feature class. here's my code example:

distList = []
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
    if lyr.name == "Disturbance":
           for row in arcpy.SearchCursor(lyr):
                if "ds" in row.Field1:
                     distList.append(row.Field1)
    lyr.definitionQuery = '"Field1"' + "in " + distList

Can anyone suggest a way to get my list into a tuple or maybe just a better way to get my items into a format where they have round brackets instead of square ones?

As a work around, I tried converting the list to string str(distList) and then replacing the brackets. That works fine, but it seems cumbersome and I'm sure there's a better way.

Thanks, Mike

Best Answer

The braces/brackets/whatever shouldn't matter, just create the string later. If you ",".join(somelist) you get the string 'String1, String2' so you can extend that:

distList = []
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
    if lyr.name == "Disturbance":
        for row in arcpy.SearchCursor(lyr):
            if "ds" in row.Field1:
                distList.append('"{}"'.format(row.Field1))
        lyr.definitionQuery = '"Field1" in ({})'.format(", ".join(distList))