You can use the special variable loop.count to track which element of a list you are at -- you don't need to handle this logic yourself.  See http://template-toolkit.org/docs/manual/Variables.html#section_loop