# How to get the number of elements in a \foreach loop?

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?

• So, are you actually asking how to obtain the length of a list? Your title (and first sentence of the body) suggest that you want to obtain it using \foreach. I suggest changing the title to something like: “Obtaining the length of a list in tikz-pgf”
– jmc
Nov 29 '13 at 13:16
• Related Question: How can I determine the size of an array? May 5 '14 at 7:49

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...
}

• unless the array is indexed... Nov 29 '13 at 20:10
• @percusse: Yes. But it is beyond the scope. :-) Nov 29 '13 at 20:11
\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}

• From the original question: "Can this be achieved without iterating the whole list once?"
– Werner
Dec 29 '13 at 20:08