Online ArcGIS resource help provides a list of layer properties which can be used as needed. I am not able to find a way to collapse a layer using ArcPy in it.
Is a way to collapse a layer in the current data frame of ArcMap using ArcPy?
It may not be a great solution but if you have saved layer files with them collapsed then RemoveLayer followed by InsertLayer sounds like it could do it:
The way a layer appears in the table of contents (TOC) after it is added depends on the source layer and how it appears. For example, some layers are completely collapsed and do not display their symbol(s) in the TOC. This setting is built into the layer. If a layer is collapsed, saved to a layer file, and then added to a map document, the layer will be collapsed in the new map document when added via InsertLayer.
However, my suggestion is that you vote for the ArcGIS Idea that Layer object in python should have a Collapse parameter.
An update to that ArcGIS Idea has been posted by jbarrette-esristaff:
This will not be supported for arcpy.mapping (ArcMap). But for Pro 2.4 we added finer grained access to many more capabilities via the CIM - Esri's Cartographic Information Model.
along with an ArcGIS Pro code sample:
p = arcpy.mp.ArcGISProject('current')
m = p.listMaps('Map')[0]
for l in m.listLayers():
if l.isGroupLayer:
l_cim = l.getDefinition('V2') #get the layer's CIM definition
l_cim.expanded = True #expand
l.setDefinition(l_cim) #set the layer's CIM definition
if l.isFeatureLayer or l.isRasterLayer:
l_cim = l.getDefinition('V2') #get the layer's CIM definition
l_cim.expanded = False #collapse
l.setDefinition(l_cim) #set the layer's CIM definition