How to Remove Feature Layer Using ArcPy Script

arcgis-10.0arcpylayers

I have an ArcPy based script where I'm trying to intersect two layers where one layer must have its centroid in the other layer.

Since I need to know that one layer (feature_layer below) includes the centroid of the other, I'm using the arcpy.SelectLayerByLocation_management() tool.

I do not have a Map Document (*.mxd) open so in order to do this, I have to use Make Feature Layer to feed into it.

The documentation notes that the feature layer will disappear when the program exits, but I need it to disappear sooner since I have it in a loop similar to below.

for feature_class in large_list_of_feature_classes:
    some_function(feature_class)

def some_function():
    feature = "{path to feature class}"
    feature_layer = "feature_layer"
    HUCs_layer = "all_HUCs" #HUCs being Hydrologic Unit Codes
    
    arcpy.MakeFeatureLayer_management(feature, feature_layer)
    arcpy.MakeFeatureLayer_management(feature, HUCs_layer)      
    arcpy.SelectLayerByLocation_management(HUCs_layer, "HAVE_THEIR_CENTER_IN", feature_layer, selection_type="NEW_SELECTION")

    arcpy.CopyFeatures_management(HUCs_layer, selection_name)

I'm looking for a function to remove feature layers and I haven't been able to find one.

I realize I could put some sort of count in there or something to make each one unique within the scope of the program, but that's not ideal unless there is no way to remove feature layers.

Best Answer

The Delete tool should accept the name of a feature layer to remove it from the TOC.

Permanently deletes data from disk. All types of geographic data supported by ArcGIS, as well as toolboxes and workspaces (folders, geodatabases), can be deleted. If the specified item is a workspace, all contained items are also deleted.

and under the Syntax section lists the Data Types that can be deleted as:

Data Element; Graph; Layer; Table View