LeafCount

LeafCount[expr]

gives the total number of indivisible subexpressions in expr.

Details and Options

Examples

open allclose all

Basic Examples  (1)

Find the number of "leaves" in an expression tree:

These are the leaves in the expression:

Options  (1)

Heads  (1)

By default, leaves in heads are included:

Exclude leaves in heads:

Applications  (3)

Find leaf count measures of the sizes of successive integrals:

Make Simplify pick expressions with minimum LeafCount:

Find leaf counts in combinator expressions [more info]:

Properties & Relations  (6)

LeafCount by default includes the head and all elements inside it:

For expressions with atomic heads, this corresponds to the number of vertices in TreeForm[expr]:

LeafCount[expr,HeadsFalse] typically gives the number of leaves in TreeForm[expr]:

LeafCount counts elements in rational and complex numbers just as in FullForm:

LeafCount counts the head and values of an Association:

These are the five leaves in the expression:

Reversing the keys and values gives a different result:

LeafCount treats atomic objects, such as SparseArray objects, as single expression leaves:

SparseArray objects have a complicated FullForm:

But they are atomic:

For most expressions, LeafCount equals the count matching Blank[] at level {-1}:

LeafCount counts Rational and Complex numbers using their FullForm:

Count treats Rational and Complex as atoms:

Possible Issues  (3)

LeafCount is based on the FullForm of expressions:

LeafCount by default includes leaves in heads:

The head f is considered a leaf, even though it is not a leaf in a tree visualization of the expression:

Use the setting HeadsFalse to only count the leaves of the tree visualization:

Unlike TreeForm, LeafCount takes into consideration the structure of expression heads:

This shows the expression tree whose leaves are counted by LeafCount:

Wolfram Research (1988), LeafCount, Wolfram Language function, https://reference.wolfram.com/language/ref/LeafCount.html (updated 2022).

Text

Wolfram Research (1988), LeafCount, Wolfram Language function, https://reference.wolfram.com/language/ref/LeafCount.html (updated 2022).

CMS

Wolfram Language. 1988. "LeafCount." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2022. https://reference.wolfram.com/language/ref/LeafCount.html.

APA

Wolfram Language. (1988). LeafCount. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/LeafCount.html

BibTeX

@misc{reference.wolfram_2024_leafcount, author="Wolfram Research", title="{LeafCount}", year="2022", howpublished="\url{https://reference.wolfram.com/language/ref/LeafCount.html}", note=[Accessed: 06-November-2024 ]}

BibLaTeX

@online{reference.wolfram_2024_leafcount, organization={Wolfram Research}, title={LeafCount}, year={2022}, url={https://reference.wolfram.com/language/ref/LeafCount.html}, note=[Accessed: 06-November-2024 ]}