Use counter before its value is set
Welcome to TeX.SE. This is a job for the totcount
package. You need to compile twice, since totcount
uses the .aux
file to store the last value assigned to the counter in the document.
Note that I use \value{enumi}
instead of \thenumi
in the \setcounter
call in case \thenumi
doesn't expand to an integer denotation (\thenumi
might use \roman
or \alph
formatting, etc.).
\documentclass{article}
\usepackage{totcount}
\begin{document}
\newtotcounter{howmany}
There are \total{howmany}~items in this list:
\begin{enumerate}
\item one
\item two
\item three
\setcounter{howmany}{\value{enumi}}
\end{enumerate}
\end{document}
If there is already a \newcounter
command for the counter in question and you don't want to, or cannot change this command into a \newtotcounter
call, you can register the counter with the totcount
package using \regtotcounter{countername}
(this can be useful if the counter is defined by a package).
This also works with non-decimal labels
This technique works as well if you use non-decimal label formatting:
\documentclass{article}
\usepackage{totcount}
\renewcommand{\theenumi}{\alph{enumi}}
\begin{document}
\newtotcounter{howmany}
There are \total{howmany}~items in this list; their labels are
\ref{first-item}, \ref{second-item}, and \ref{third-item}.
\begin{enumerate}
\item \label{first-item}one
\item \label{second-item}two
\item \label{third-item}three
\setcounter{howmany}{\value{enumi}}
\end{enumerate}
\end{document}
You can wrap your list to be counted in an environment:
\documentclass{article}
\makeatletter
\newenvironment{countitems}[1]
{% #1 is the label for referring to the count
\def\countitems@label{#1}%
}
{%
\edef\@currentlabel{\arabic{enum\romannumeral\numexpr\@enumdepth+1}}%
\label{\countitems@label}%
\ignorespacesafterend
}
\makeatother
\begin{document}
The following list has \ref{firstlist} items
\begin{countitems}{firstlist}
\begin{enumerate}
\item one
\item two
\item three
\begin{countitems}{innerlist}
\begin{enumerate}
\item A
\item B
\end{enumerate}
\end{countitems}
\end{enumerate}
\end{countitems}
The inner list has \ref{innerlist} items.
\end{document}
Alternatively, you can use a command after the relevant \end{enumerate}
\documentclass{article}
\makeatletter
\newcommand{\countitems}[1]{%
\edef\@currentlabel{\arabic{enum\romannumeral\numexpr\@enumdepth+1}}%
\label{#1}%
\ignorespaces
}
\makeatother
\begin{document}
The following list has \ref{firstlist} items
\begin{enumerate}
\item one
\item two
\item three
\begin{enumerate}
\item A
\item B
\end{enumerate}\countitems{innerlist}
\end{enumerate}\countitems{firstlist}
The inner list has \ref{innerlist} items.
\end{document}