I want to iterate through a layer that has about 500 records. In my code, I'm using a definition query inside a for loop to iterate through a test list:

listx = [1,2,3,4,5]

My question (probably an elementary one), is how to just call out all records instead of manually typing all 500 object ID's? I want to iterate through all Object IDs, while ingesting each ID into the definition query. I thought trying [:] or [*] or [0:500] would work, but they don't.

import arcpy
from arcpy import mp

p  = arcpy.mp.ArcGISProject("CURRENT")
m = p.listMaps("Map")[0]

lyr1 = m.listLayers("No_Other")[0]
lyr2 = m.listLayers("No_Admin")[0]

#obid = "OBJECTID in (409, 764, 114, 776)"
obid = "OBJECTID = {}"
listx = [114, 409, 764, 776]

for oid in listx:
    lyr2.definitionQuery = obid.format(oid)
    arcpy.SelectLayerByLocation_management(lyr1, 'WITHIN_A_DISTANCE', lyr2, "150 Miles", 'ADD_TO_SELECTION', 'NOT_INVERT')
    lyr2.definitionQuert = None

2 Answers 2


You can try something like this:

oids = ''
for x in listx:
    oids = oids + str(x) + ','
query = 'OBJECTID IN (' + oids[:-1] + ')'

Then give this query to your Selection call. The reason for the [:-1] is that the final ',' needs to be removed for the SQL query to work.

If you simply want to select all features with your query, use "OBJECTID IS NOT NULL" and that will return everything.

  • Thanks, but what do I pass in for 'listx' if I'm replacing listx with the query line?
    – Dave
    Jan 12, 2018 at 18:50
  • If you have a list (listx) of certain features, you can create a query from that to pass using this. If you mean that you want to select all features, you don't need a query at all. If that's the case, use a line like what @BERA has presented. But per your original question, this would work.
    – AlecZ
    Jan 12, 2018 at 19:21
  • Yes, looks like I'm trying to do more of what @BERA recommended. How do I compensate for the commas in the list defined by the 'oids' statement? Asking because, the definition query is failing and stopping at "OBJECTID = (1,)", so it's not proceeding to the next OBJECTID.
    – Dave
    Jan 12, 2018 at 19:31
  • See the updated answer above
    – AlecZ
    Jan 12, 2018 at 19:50
  • I think I'm still missing something in your answer. I understand the inclusion of [:-1], but the values returned look like: "(1,)". For some reason it's putting all ObjectID values inside parens.
    – Dave
    Jan 12, 2018 at 20:14

Not sure i understand your question but to list all objectids:

import arcpy

fc = r'C:\database.gdb\feature_class' #Change to match your data. It can also be a feature layer with a definition query

oids = [i for i in arcpy.da.SearchCursor(fc, 'OID@')]

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.