I'm writing a macro that takes a list of numbers as its only parameter. When I iterate through the list, I'd like to keep track of the index of the item in the list. Here's an example of what I want:

% \myMacro{2,1,3} \\ % this is the same as what follows

  \draw (1,0) -- +(0,2);
  \draw (2,0) -- +(0,1);
  \draw (3,0) -- +(0,3);

Pretending that \index is the way to get what I want, I'd write this macro as:

    \foreach \height in #1 {
      \draw (\index,0) -- +(0,\height);

Is there a way to do this? I know that, if I wanted to call it as \myMacro{2/1,1/2,3/3}, I could replace one line with \foreach \height/\index in #1 {, but I'd much prefer to not need to pass the indicies in the parameter.

  • 1
    For future, please don't post code fragments, but instead put the fragment into a minimal compilable document (even if it gives an error) like I did in my answer.
    – Alan Munn
    Jul 12, 2017 at 17:19

1 Answer 1


The pgffor package (part of tikz) provides a count key for this which you can assign to a macro. Note that you need { } around the #1 in your macro definition.

    \foreach \height [count=\myindex] in {#1} {
      \draw (\myindex,0) -- +(0,\height);

output of code

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.