[Tex/LaTex] For loop print out array contents sequentially

loops

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

Best Answer

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

\documentclass{article}
\usepackage{pgf,pgffor}% http://ctan.org/pkg/{pgf,pgffor}
\begin{document}
\foreach \x [count=\xi] in {a_1,a_2,a_3} {%
  \ifnum\xi=1
    $\x$%
  \else
    $,\x$%
  \fi
} \par
\foreach \x [count=\xi] in {1,...,10} {%
  \ifnum\xi=1
    $b_1$%
  \else
    $,b_{\xi}$%
  \fi
}
\end{document}