Beamer Code Snippets Slide by Slide

I would like my slide presentation to display one item at a time, where the codesnippet is considered another item. Here's what I have.

\documentclass{beamer}
\usepackage{listings}
\begin{document}

\begin{frame}[fragile]
\frametitle{Test Slide}

\defverbatim[colored]\codesnippet{
\begin{lstlisting}[language=Python,basicstyle=\ttfamily,keywordstyle=\color{blue}]
def main():
<statements>
\end{lstlisting}
}

\begin{itemize}
\item<1-> test
\item<2-> test
\codesnippet
\end{itemize}
\end{frame}

\end{document}


What happens with my current code is that item<1-> appears on the first slide, but then item 1 and item 2 appear on the second slide together with codesnippet. On slide 2, I just want item 1 and item 2 without the codesnippet, and then have item 1, item 2, and codesnippet appear on slide 3. If i try to nest codesnippet in another item like so, then I get an extra item after the code snippet.

\begin{itemize}
\item<1-> test
\item<2-> test
\item<3->{\codesnippet}
\end{itemize}


How can I treat a code snippet like an item that can be added to the next slide? Thanks.

• Welcome ! You are misunderstanding the meaning of the overlay specifications you use. When using <x-y> means that something will be shown on frames x to y. So if you want everything to appear alone, just ommit the -. Have a look at the \only and \onslide commands too.You could remplace your itemize with \begin{itemize}item<1> test\item<2> test\end{itemize}\only<3>{\codesnippet}\end{frame}\end{document} Apr 16 '20 at 21:16
• Hello, thank you so much for the response! I realize that my question is actually not clearly written. I didn't mean to say that I want everything appearing alone on a slide, what I meant was that items appear sequentially on top of the past items and the code snippet is like another item. For example, on slide 2, I want just item 1 and item 2, and NOT the code snippet. On slide 3, I want item 1, item 2, and the codesnippet. I will edit the original question for clarity. Apr 19 '20 at 1:40

Well, I do not know why, but the problem seems to come from the definition of \codesnippet. If you replace it with the explicit expression of its content, it works fine. Do you really need to define this macro ?

\documentclass{beamer}
\usepackage{listings}
\lstset{language=Python,basicstyle=\ttfamily,keywordstyle=\color{blue}}
\begin{document}

\begin{frame}[fragile]
\frametitle{Test Slide}

\begin{itemize}
\item<1-> test
\item<2-> test
\item<3->
\begin{lstlisting}
def main():
<statements>
\end{lstlisting}
\end{itemize}
\end{frame}

\end{document}

• Thank you! This does work. The macro was definitely not mandatory, it was a post on creating code listings so I just used that format. Apr 24 '20 at 2:39