# Color names in foreach loop

Edit: I can't delete this question despite it being based on a silly mistake. Please don't waste time reading/answering.

I'm trying to draw a row of boxes which alternate colours, and I'm using a \foreach to do it. My question is whether it's possible to use colour names as a variable in a foreach loop.

MWE:

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\foreach \x/\y {1/blue, 2/red, 3/blue, 4/red}
\fill[color=\y] (\x,0) --++ (1,0) --++ (0,1) --++ (-1,0) --cycle;

\end{tikzpicture}
\end{document}


When I run this I get the error ! Package pgfkeys Error: I do not know the key '/pgf/foreach/color', to which you passed '\y ', and I am going to ignore it. Perhaps you misspelled it.

In other questions I've seen (example 1, example 2, example 3), people have been asking about defining colours with numbers (red!50!black, for example), so I think this question is different.

So, am I just doing something wrong, or is it simply not possible to do what I'm trying to do. If it's the latter, I'll do it a different way, but I wanted to know about the possibility.

• Haha, I usually find this SE forum to have the nicest community! When someone makes a silly mistake on others like SO they'll get downvoted and then forced to delete their post. May 28 '18 at 1:45

\foreach \x/\y in {..}. You forgot in.

By the way, it's a bit shorter with rectangle:

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\foreach \x/\y in {1/blue, 2/red, 3/blue, 4/red}
\fill[color=\y] (\x,0) rectangle +(1,1);

\end{tikzpicture}
\end{document}

• "You forgot in." Ooh dear. That's embarrassing. May 27 '18 at 14:53

A slightly different approach:

• you don't need color= in your fill command

• maybe a single loop while counting another variable is simpler

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\foreach \y [count=\x] in {blue, red, blue, red} {
\fill[\y] (\x,0) --++ (1,0) --++ (0,1) --++ (-1,0) --cycle;
}

\end{tikzpicture}
\end{document}

• Maybe with \ifodd it would be even nicer... (+1)
– user121799
May 27 '18 at 15:10
• @marmot Thanks for your vote :) If the colours are strictly alternating, \ifodd is certainly the much easier way. May 27 '18 at 15:14