I am using pythontex to read in a large python list from disk into my .tex file; I wish to use the \foreach command from the tikz package to do some typesetting for each of the items in the list.
MWE is as follows:
\documentclass{article}
\usepackage{pythontex}
\usepackage{tikz}
\begin{document}
\begin{pycode}
some_letters = ['A', 'B', 'C']
\end{pycode}
normal for-loop:\\
\foreach \letter in {a, b, c} {letter=\letter\\}
for-loop with \texttt{pythontex}:\\
\foreach \letter in {\py{some_letters}} {letter=\letter\\}
\end{document}
and is typeset as follows:
normal for-loop:
letter=a
letter=b
letter=c
for-loop with pythontex:
letter=['A', 'B', 'C']
The first for-loop displays correctly. The second for-loop is where I attempt to read the python list. \py{} returns the python object and what I want are comma separated values like in the first for-loop. I have unsuccessfully tried the following instead of \py{some_letters}:
\py{*some_letters} % attempt to explode the python list
\py{','.join(some_letters)} % manually separate with commas
% and defining a generator function to yield one value at a time
Does anyone know how I can use the \foreach command with a python iterable? The desired output is as follows:
normal for-loop:
letter=a
letter=b
letter=c
for-loop with pythontex:
letter=A
letter=B
letter=C
update 1
The following is what I am using the after getting help from @whatisit
\documentclass{article}
\usepackage{pythontex}
\usepackage{tikz}
\begin{document}
\begin{pycode}
some_letters = ['A', 'B', 'C']
\end{pycode}
\newcommand{\dosomething}{letter=\letter\\}
normal for-loop:\\
\foreach \letter in {a, b, c} {\dosomething}
for-loop with \texttt{pythontex}:\\
\pyc{print('\\foreach \\letter in {{{}}} {{\\dosomething}}'.format(','.join(some_letters)))}
\end{document}
The \pyc{} command is the inline version of the pycode environment so it should work the same for these purposes. I defined the for-loop contents in \dosomething{} so that I can take advantage of my LaTeX IDE syntax highlighting.
update 2
The following uses the \pys{} command which is the inline version of the pysub environment to substitute anything inside !{python_code}. Otherwise everything else inside the \pys{} command can be left as normal latex source code.
\documentclass{article}
\usepackage{pythontex}
\usepackage{tikz}
\begin{document}
\pyc{some_letters = ['A', 'B', 'C']}
normal for-loop:\\
\foreach \letter in {a, b, c} {letter=\letter\\}
for-loop with \texttt{pythontex}:\\
\pys{\foreach \letter in {!{','.join(some_letters)}} {letter=\letter\\}}
\end{document}

\py{print("\\foreach \\letter in {"+','.join(some_letters)+"} {letter=\\letter\\\\}")}Basically, rather than printing just that list, you want to print the entire line of LaTeX so that everything is processed at the correct time. The only issue with this is that printing the list results in something creatingNone...I'm not immediately sure what the problem is. – whatisit Jan 09 '19 at 01:26