Layouts can contain a large number of elements, many of which you won't need for a particular geoprocessing script. The ListLayoutElements()
function can restrict the layout elements returned, by passing a parameter that defines the type of element that should be returned along with an optional wildcard, which finds elements using a portion of the name.
There are many different types of layout elements, including graphics, legends, pictures, text, and data frames. When you return a list of layout elements, you can restrict (filter) the types of elements that are returned. In this recipe, you will write a script that filters the layout elements returned by element type and wildcard.
Follow these steps to learn how to restrict the list of layers returned by the ListLayoutElements()
function through the use of optional parameters, which define the type of element that should be returned along with a wildcard that can also restrict the elements that are returned:
C:ArcpyBookCh4Crime_Ch4.mxd
in ArcMap.arcpy.mapping
module:import arcpy.mapping as mapping
Crime_Ch4.mxd
) and assign this reference to a variable:mxd = mapping.MapDocument("CURRENT")
ListLayoutElements()
function with a restriction of only legend elements, as well as a wildcard that returns elements with a name containing the Crime
text anywhere in the name:for el in mapping.ListLayoutElements(mxd,"LEGEND_ELEMENT","*Crime*"): print(el.name)
c:ArcpyBookcodeCh4RestrictLayoutElements.py
solution file.Crime Legend
ListLayoutElements()
is a versatile function, which in its most basic form is used to return a list of all the layout elements on the page layout of a map document. However, there are two optional parameters that you can supply to filter this list. The first type of filter is an element type filter in which you specify that you only want to return one of the layout element types. You can also apply a wildcard to filter the returned list. These two types of filters can be used in combination. For example, in this recipe, we are specifying that we only want to return LEGEND_ELEMENT
objects with the Crime
text anywhere in the element name. This results in a highly filtered list that only contains a single layout element.