10

Does the PGF command \foreach provide a simple possibility to get the number of elements iterated?

It has a parameter count to hold the current element number, so a workaround is to iterate the list once. After execution, the last count is the number of elements in #1.

\foreach \letter [count=\n] in {#1} {}
% \n now keeps the number of elements.

Can this be achieved without iterating the whole list once?

XZS
  • 2,953

2 Answers2

5
\documentclass{minimal}
\usepackage{tikz}
\newcounter{dummy}
\def\getNoOfElements#1#2{%
  \setcounter{dummy}{0}% 
  \foreach\dummy in {#1}{\stepcounter{dummy}}%
  \edef#2{\arabic{dummy}}
}
\begin{document}

\getNoOfElements{a,b,c,d,e,f}\No % save the value in \No
\No

\getNoOfElements{1,2,3,4}\No
\No

\end{document}
  • 4
    From the original question: "Can this be achieved without iterating the whole list once?" – Werner Dec 29 '13 at 20:08
3

It is impossible to know the number of elements in a list without at least iterating the list once. I don't think you want the following tricks.

\def\procedure#1#2{%
%#1 comma separated elements
%#2 the number of elements in the list
\foreach \letter in {#1} {}%
% use the #2 here...
}