Menu

Get Layer Selected Feature Count Using Python

03 December 2014

Update 20 minuts after posting: I remembered the GetCount_management tool honors selections. Hence, if you use this tool, it does the same thing. This mostly means this post is an exercise in reinventing the wheel.

Recently in a script I needed to get a count of selected features in a layer. Cobbling together a few functions, this can be accomplished in one line of code, although at first it appears somewhat daunting to discern. Here is the finished product.

len(arcpy.Describe(selLyr).FIDSet.split('; '))

To understand what is happening, start with the innermost set of parenthesis. Here, selLyr is the only variable in this function. This variable I arbitrarially named and set to reference the layer with features selected.

These features may have been selected interactively in ArcMap, and this fucntion is evaluating an active layer in ArcMap from the interacive Python prompt. Alternatively, you can also have a stand alone Python script, use MakeFeatureLayer_management to create a layer in memory and select features in this layer using SelectLayerByAttributes_management to select features. Either way, the above snippet is useful for getting a list of features selected in Python.

Next, we use call the Describe method with this layer as the parameter. This method returns a Describe object.

arcpy.Describe(selLyr)

Calling the Describe method is just like opening the properties window in ArcMap for a layer...except in Python. It enables access to examine properties of the layer in Python, eanbling access to all the properites and methods of a Layer Describe objet.

The Layer Desscribe object properties and methods include the FIDSet property. This property returns a string of selected feature ID's separated by semicolons. Now, our snippet looks like this.

arcpy.Describe(selLyr).FIDSet

The string returned from this property can be separted into a list of FID values using the Python split string method. Split takes a parameter for specifying what delimter to search for when splitting the string into a list. In our case, we are looking for a semicolon followed by a space. Putting everything toegether looks like this.

arcpy.Describe(selLyr).FIDSet.split('; ')

Since the above returns a list, the final step is to get the count of selected elements in the layer by getting the length of the list using the length method len(object).