I am able to run the below code in the Python command window in ArcMap 10.2.1 without issue. However, when I run this as a toolbox script, it fails at line 15:
newLyr = arcpy.mapping.ListLayers(mxd, "New Feature Layer", df)[0]
IndexError: list index out of range
It seems to me that the feature layer is not being generated in line 14, causing the error in the following line. But I'm not sure. Does anyone have any idea why the processing would fail when executed as a script but not when run in the command window?
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
arcpy.Delete_management("New Feature Layer") #clear any earlier instance from memory
attrLyr = arcpy.mapping.ListLayers(mxd, "SELECT FEATURES BY ATTR LAYER", df)[0]
locLyr = arcpy.mapping.ListLayers(mxd, "SELECT FEATURES BY LOCATION LAYER", df)[0]
srcLyr = arcpy.mapping.ListLayers(mxd, "SRC SYMBOLOGY LAYER", df)[0]
expression = "SELECTION EXPRESSION"
arcpy.SelectLayerByAttribute_management(attrLyr,"NEW_SELECTION",expression) #select features from attrLyr according to expression
arcpy.SelectLayerByLocation_management(locLyr, "INTERSECT", attrLyr) #select features from locLyr that intersect with attrLyr
arcpy.MakeFeatureLayer_management(locLyr, "New Feature Layer") #create feature layer from selected features in locLyr
newLyr = arcpy.mapping.ListLayers(mxd, "New Feature Layer", df)[0] #assign new layer to variable "newLyr"
arcpy.mapping.UpdateLayer(df, newLyr, srcLyr, True) #apply srcLyr symbology to newLyr