]> granicus.if.org Git - python/commitdiff
Documentation for the enumerate() function/type.
authorFred Drake <fdrake@acm.org>
Fri, 26 Apr 2002 20:29:44 +0000 (20:29 +0000)
committerFred Drake <fdrake@acm.org>
Fri, 26 Apr 2002 20:29:44 +0000 (20:29 +0000)
This closes SF patch #547162.

Doc/lib/libfuncs.tex
Doc/tut/tut.tex

index 3192a176051680c534e71d4512913349bda115b9..c7bb5a628f86c0bdcc5604f2825aa7da9d256de6 100644 (file)
@@ -261,6 +261,18 @@ def my_import(name):
   \var{b}, and \code{0 <= abs(\var{a} \%{} \var{b}) < abs(\var{b})}.
 \end{funcdesc}
 
+\begin{funcdesc}{enumerate}{iterable}
+  Return an enumerate object. \var{iterable} must be a sequence, an
+  iterator, or some other object which supports iteration.  The
+  \method{next()} method of the iterator returned by
+  \function{enumerate()} returns a tuple containing a count (from
+  zero) and the corresponding value obtained from iterating over
+  \var{iterable}.  \function{enumerate} is useful for obtaining an
+  indexed series: \code{(0, seq[0])}, \code{(1, seq[1])}, \code{(2,
+  seq[2])}, \ldots.
+  \versionadded{2.3}
+\end{funcdesc}
+
 \begin{funcdesc}{eval}{expression\optional{, globals\optional{, locals}}}
   The arguments are a string and two optional dictionaries.  The
   \var{expression} argument is parsed and evaluated as a Python
index d7d363c105dfc41c810108effb21f2e6f06cc35c..49f36b7a94261dcba779221f5caf743d33d36e3a 100644 (file)
@@ -2014,6 +2014,49 @@ Here is a small example using a dictionary:
 1
 \end{verbatim}
 
+
+\section{Looping Techniques \label{loopidioms}}
+
+When looping through dictionaries, the key and corresponding value can
+be retrieved at the same time using the \method{items()} method.
+
+\begin{verbatim}
+>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
+>>> for k, v in knights.items():
+...     print k, v
+...
+gallahad the pure
+robin the brave
+\end{verbatim}
+When looping through a sequence, the position index and corresponding
+value can be retrieved at the same time using the
+\function{enumerate()} function.
+
+\begin{verbatim} 
+>>> for i, v in enumerate(['tic', 'tac', 'toe']):
+...     print i, v
+...
+0 tic
+1 tac
+2 toe
+\end{verbatim}
+
+To loop over two or more sequences at the same time, the entries
+can be paired with the \function{zip()} function.
+
+\begin{verbatim}
+>>> questions = ['name', 'quest', 'favorite color']
+>>> answers = ['lancelot', 'the holy grail', 'blue']
+>>> for q, a in zip(questions, answers):
+...     print 'What is your %s?  It is %s.' % (q, a)
+...    
+What is your name ?  It is lancelot .
+What is your quest ?  It is the holy grail .
+What is your favorite color ?  It is blue .
+\end{verbatim}
+
+
 \section{More on Conditions \label{conditions}}
 
 The conditions used in \code{while} and \code{if} statements above can