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

%#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. :-) Nov 29 '13 at 20:11
  \foreach\dummy in {#1}{\stepcounter{dummy}}%

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


  • 4
    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.