TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have already some experience getting \forloop to work in LaTeX but I can't figure out how to get it to print off each item sequentially in a given "array"... Like this pseudo-code would do:

\foreach \n in {a_1,a_2,a_3}{a_i, }

would give:

a_1, a_2, a_3

(notice the lack of a comma after a_3).

share|improve this question

migrated from stackoverflow.com Feb 5 '12 at 7:28

This question came from our site for professional and enthusiast programmers.

up vote 3 down vote accepted

Here is a way using the count key to store the current index. This allows you to use a different printing style/technique for the first item:

enter image description here

\usepackage{pgf,pgffor}% http://ctan.org/pkg/{pgf,pgffor}
\foreach \x [count=\xi] in {a_1,a_2,a_3} {%
} \par
\foreach \x [count=\xi] in {1,...,10} {%
share|improve this answer

This is a programming question, not a TeX question, though since TeX is a programming language, it has a TeX answer. The answer is that you have to be able to tell TeX what the last iteration in the loop is so it can behave differently. One easy (but clunky-looking) way is to write

\foreach \n in {a_1, a_2} {$\n$, }$a_3$

(since this is TeX, I've taken the liberty of putting math-mode around the a_i; not doing this will give an error from the subscript). Another way is to define a "conditional comma", say

\foreach \n [count = \c from 1] in {a_1, a_2, a_3} {\comma{\c}$\n$}

which will print a comma after the count \c (recording the number of items printed in the list) passes 1. This avoids the need to update the "last term" code every time you tweak the list. (Obviously better algorithm is taken from Werner's answer.)

Here I've used the etoolbox package, which is quite useful (though overkill for just this one thing) and the facility of \foreach to count iterations in its loop. You should read section 56 of the PGF-2.10 manual, which is short and describes the general behavior of this "function". (There are no actual functions in TeX.)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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