9

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?

  • 2
    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? – Peter Grill May 5 '14 at 7:49
2

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... – percusse Nov 29 '13 at 20:10
  • @percusse: Yes. But it is beyond the scope. :-) – kiss my armpit Nov 29 '13 at 20:11
2
\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}
  • 3
    From the original question: "Can this be achieved without iterating the whole list once?" – Werner Dec 29 '13 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.