[Tex/LaTex] Comma delimited list – how to obtain the length

comma-separated listloops

It's simple. I have a list like {0,1,54,1,3} as input argument to a command in making. How can I obtain the length of this list? Something like

\length(#1)

where #1 is the list.

Best Answer

My first LaTeX3 answer! Yay! :)

The l3clist package has a lot of built-in commands to deal with comma-separated lists. Here's an attempt:

\documentclass{article}

\usepackage{expl3}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand \countItems { m } {
    \clist_count:N #1
}

\NewDocumentCommand \countInlineItems { m } {
    \clist_count:n {#1}
}

\ExplSyntaxOff

\begin{document}

\def\mylist{0,1,54,1,3}

This list has \countInlineItems{0,1,54,1,3} elements.

And the same list has \countItems{\mylist} elements.

\end{document}

Please note that we have two different usages: one for a stored list (e.g, \mylist) and one for an inline list. Thanks to Joseph for point the flaws in my code. :)

Hope it helps. :)