6

How can I make a TikZ foreach loop iterate over two lists consecutively? I had hoped that in my code below, the expression \firstlist,\secondlist would evaluate to 2,3,5,7,1,4,6, but it doesn't work. I have tried mild variants, like {\firstlist,\secondlist} and \firstlist\secondlist, without success.

\documentclass{article}
\usepackage{tikz}
\begin{document}

\def\firstlist{2,3,5,7}
\def\secondlist{1,4,6}

\begin{tikzpicture}
 \foreach\x in \firstlist,\secondlist
  \node[shape=circle,draw=black] at (\x,0) {\x};
\end{tikzpicture}

\end{document}
2
  • 2
    I don't think that this can be done. The foreach loop expects either a single macro or a comma-delimited list. So either it just sees the \firstlist or it sees a two-element list {\firstlist,\secondlist}. You could do a double loop: \foreach \list in {\firstlist,\secondlist} \expandafter\let\expandafter\list\list \foreach \x in \list ... but that's not all that pretty! I think that creating an amalgam out of the two lists before the \foreach would be best. Commented May 23, 2013 at 9:26
  • 2
    The amalgam can be defined via \edef\amalgamlist{\firstlist,\secondlist} then \foreach \x in \amalgamlist .... Commented May 23, 2013 at 9:29

1 Answer 1

6

You can also use \newforeach:

\usepackage{tikz}
\usepackage{loops}[2013/05/01]
\begin{document}

\def\firstlist{1,3,...,9}
\def\secondlist{2,4,...,10}

\begin{tikzpicture}
 \newforeach[expand list] \x in {\firstlist,\secondlist}
  \node[shape=circle,draw=black] at (\x,0) {\x};
\end{tikzpicture}

\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .