From 56bb8b9bdc2626ae6d5097cd4ef6aac6d2ab015f Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Sat, 30 Mar 2013 23:37:57 -0700 Subject: [PATCH] Add an itertools recipe showing how to use t.__copy__(). --- Doc/library/itertools.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index a7f0058b4cd..0e98c1e2adf 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -828,6 +828,18 @@ which incur interpreter overhead. indices = sorted(random.randrange(n) for i in xrange(r)) return tuple(pool[i] for i in indices) + def tee_lookahead(t, i): + """Inspect the i-th upcomping value from a tee object + while leaving the tee object at its current position. + + Raise an IndexError if the underlying iterator doesn't + have enough values. + + """ + for value in islice(t.__copy__(), i, None): + return value + raise IndexError(i) + Note, many of the above recipes can be optimized by replacing global lookups with local variables defined as default values. For example, the *dotproduct* recipe can be written as::