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
\usepackage{etoolbox}
\newcommand\comma[1]{\ifnumgreater{#1}{1}{,}{}}
\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.)