Select to view content in your preferred language

"IndexError: list index out of range" - when trying to Update Layer in ArcPy

3797
10
10-05-2011 03:07 PM
KateNewell
Deactivated User
Hi!
I am trying to run (what I thought) was a very simple script that updates the symbology in a Layer File based on another layer file. Being very new to Python, I "lifted" some example code straight from the ArcGIS10 help ( http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/UpdateLayer/00s30000003p000000/ )
The layer file to be updated in my map document is part of a grouped layer file within a grouped layer file.
I keep getting an IndexError and I have no idea why!?! There is only one dataframe (Layers). Any help is greatly appreciated!

Here is my code:

import arcpy
mxd = arcpy.mapping.MapDocument(r"N:\Templates\v10\Base Maps\A_Portrait.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
updateLayer = arcpy.mapping.ListLayers(mxd, "Base Map Layers\Bay, Lakes & Streams", df)[0]
sourceLayer = arcpy.mapping.Layer(r"N:\Users\ke\Bay, Lakes & Streams.lyr")
arcpy.mapping.UpdateLayer(df, updateLayer, sourceLayer, True)
mxd.save()
del mxd, sourceLayer


and this is the error message that I get:
====
>>>
Traceback (most recent call last):
File "N:\Users\ke\ArcPyMapping\UpdateLayerFile.py", line 4, in <module>
updateLayer = arcpy.mapping.ListLayers(mxd, "Base Map Layers\Bay, Lakes & Streams", df)[0]
IndexError: list index out of range
Tags (2)
0 Kudos
10 Replies
JeffBarrette
Esri Regular Contributor
My mistake.  I included the [0] accidentally.  Let me try again:

myLayerObj = arcpy.mapping.ListLayers(mxd, "filter")[0]

This returns a layer object

myLayerListObj = arcpy.mapping.ListLayers(mxd, "filter")

This returns a Python list object.  If you want to get to items in the list you need to either use and index number or a for loop.  If your MXD is designed with all layers having unique names, then if you use the correct filter, you will only have one item in your list and you can use [0] to extract it.

There is a new arcpy.mapping tutorial that covers this in much better detail.

http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/Getting_started_with_arcpy_mapping_tut...

Jeff
0 Kudos