]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Backport 1.160 on looping idioms. Excludes enumerate(), a Py2.3 feature.
authorRaymond Hettinger <python@rcn.com>
Sat, 5 Oct 2002 05:14:19 +0000 (05:14 +0000)
committerRaymond Hettinger <python@rcn.com>
Sat, 5 Oct 2002 05:14:19 +0000 (05:14 +0000)
Doc/tut/tut.tex

index a9ae9b41cb5af5ceb02fd849c01c9b6fff505585..0d4a1f240ea207aaca9d2067f492ce2df6a22914 100644 (file)
@@ -2046,6 +2046,35 @@ pattern, list comprehensions can compactly specify the key-value list.
 \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}
+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