3

I have a feature class that has a field of unique ID numbers. I would like to create an array of these numbers so I can loop over them in ArcPy. Any ideas?

13

If you have Arc 10.1 or above, I'd use an arcpy.da cursor. Also specify just the field(s) you want.

myLayer = 'YourLayer'
myField = 'YourField'

myList = [row[0] for row in arcpy.da.SearchCursor(myLayer, myField)]
  • +1 A list comprehension will further increase the efficiency of the da Search Cursor. – Aaron Jun 3 '15 at 19:30
  • +1 as well. Comprehensions are a great python tool that everyone who uses arcpy should be familiar with. – dblanchett Jun 4 '15 at 9:40
4

Use a cursor to add to a list. The use the list for whatever.

myList = []
rows = arcpy.SearchCursor(YOURLAYER)
for row in rows:
  if row.YOURFIELD not in myList:
    myList.append(row.YOURFIELD)
del rows
del row
  • I guess it is worth noting that you can access your values differently than the row.YOURFIELD method I am using. You can use a row.getValue("YOURFIELD") to accomplish the same thing. Also, I have seen posts on here saying that recurvata's answer of using the da cursor may be faster. I just like avoiding dealing with row indices if I can. – Branco Jun 3 '15 at 19:25
  • 1
    It's those indices which improve performance. Getter lookups by name have a fearsome impact on performance, especially with a large number of columns, which is why the 1.4 FGDB API now has index lookups. – Vince Jun 4 '15 at 2:42
  • 1
    Good point. I prefer using the lookups (performance aside). The main reason is I write the code and give it to others to modify and use. Sadly, none of them really have an idea on what an index is or how to apply it. It is easier to tell them to change the field names instead of figuring out an index. If it is a larger dataset, it is definitely worth the time learning the da cursors. – Branco Jun 4 '15 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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