2

Let us assume this example

\documentclass{article}
\newcommand\printlist[1]{
  Loop to get each element \el and its index \ind from {#1}{
    \ind. \el\\
  }
}
\begin{document}
\printlist{A, B, C}
\end{document}

It would give the output

enter image description here

How to implement the loop to get each element and its index from the array {#1}?

4

What about using a \foreach?

\documentclass{article}
\usepackage{tikz}
\newcommand{\printlist}[1]{%
\foreach \x [count=\xi] in {#1} {\xi. \x\par}%
}
\begin{document}
    \printlist{A, B, C}
\end{document}

enter image description here

1

The simplest way I know is to use expl3:

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\printlist}{m}
 {
  \begin{enumerate}
  \clist_map_inline:nn { #1 } { \item ##1 }
  \end{enumerate}
 }
\ExplSyntaxOff

\begin{document}

\printlist{A,B,C}

\end{document}

The function \clist_map_inline:nn takes each (comma separated) item from its first argument and passes it as #1 for processing as specified in the second argument. Here the # has to be doubled in the second argument, so we need ##1, because we're using it in a definition.

  • That did not give the OP the index of the item as well. – daleif Dec 29 '17 at 13:55
  • @daleif I based the answer on the expected output; I think it's the usual XY type of question. – egreg Dec 29 '17 at 14:01
  • #1 in \clist_map_inline:nn { #1 } indicates the argument of \printlist? – Viesturs Dec 29 '17 at 14:15
  • @daleif, this is not an XY question. An answer about iteration is never complete without a coverage on how to get the iteration index. – Viesturs Dec 29 '17 at 14:46
  • 1
    @egreg I make up a very simple MWE to identify building blocks for a more sophisticated code. – Viesturs Dec 29 '17 at 20:31

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.