1

this gives me a list of all 55 layers in my mxd

import arcpy 
mxd = arcpy.mapping.MapDocument("CURRENT") 
df = arcpy.mapping.ListDataFrames(mxd, "Layer")[0] 
for lyr in arcpy.mapping.ListLayers(mxd, "*", df):
    print lyr.name

What I want to do is get the index number of a specific layer. For example, I want to look for the layer named 'Water' and I want the script to tell me "Water' is at position 50, so I know to look for it at the bottom on the TOC.

How can I do this?

3 Answers 3

6

What you are looking for is enumerate.

import arcpy 
mxd = arcpy.mapping.MapDocument("CURRENT") 
df = arcpy.mapping.ListDataFrames(mxd, "Layer")[0] 
for i,lyr in enumerate(arcpy.mapping.ListLayers(mxd, "*", df)):
    print "Layer {0}: {1}".format(i, lyr.name)
0
5

You could use the index() method:

import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT") 
df = arcpy.mapping.ListDataFrames(mxd, "Layer")[0]
lyrNameList = []
for lyr in arcpy.mapping.ListLayers(mxd, "*", df):
    lyrNameList.append(lyr.name)
print lyrNameList.index("Land Use")
3

I would use enumerate.

>>> x = ['a','b','c']
>>> for index,y in enumerate(x):
...     print index,y
...
0 a
1 b
2 c

Or from your snippet:

for i,lyr in enumerate(arcpy.mapping.ListLayers(mxd, "*", df)):
    print i,lyr.name
1
  • Enumerate pointed me in the right direction. I just had to add a conditional if statement to do what I wanted to do - find the position of a specific layer... if lyr.name == "Land Use": before the print line.
    – detroit_hc
    Commented Jul 6, 2013 at 21:52

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