Move a layer to a group using Python code in ArcGIS Pro


I am trying to move a layer to a group using python code. Both the layer and the group are in the current/same map in ArcGIS Pro.

I have the following code (the layer to be moved to the group "VMS" is "Fishnet_v1_manual")

import arcpy
aprx ="CURRENT")
mp = aprx.listMaps()[0]
lyr_to_move = mp.listLayers("Fishnet_v1_manual")
group_layer = mp.listLayers("VMS")
mp.addLayerToGroup(group_layer, lyr_to_move, "AUTO_ARRANGE")

But I keep getting this error:

I have also tried moving the layer to after the first layer in the group using moveLayer, but still get a similar error message as the above. The code I used for this is:

import arcpy
aprx ="CURRENT")
mp = aprx.listMaps()[0]
lyr_to_move = mp.listLayers("Fishnet_v1_FeatureLayer_v3")
ref_layer = mp.listLayers(r"Data points in grid")
mp.moveLayer(ref_layer, lyr_to_move, "AFTER")

The error message is:


Any ideas on how to fix this error or are there other ways of moving a layer to a group in the current map?

Best Answer

The help file states that listLayers() - Returns a Python list of Layer objects that exist within a map.

So in your code lyr_to_move is a list object.

To retrieve the layer from the list to feed into the addLayerToGroup() you would use the following code:

lyr_to_move = mp.listLayers("Fishnet_v1_manual")[0]