diff options
Diffstat (limited to 'itertoolset.py')
-rw-r--r-- | itertoolset.py | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/itertoolset.py b/itertoolset.py index 8d94e14..498b940 100644 --- a/itertoolset.py +++ b/itertoolset.py @@ -2,6 +2,19 @@ from itertools import * import collections from copy import deepcopy +def peek(iterable): + """Peek at the first element of `iterable`. + + Returns a tuple of the form (first_element, iterable). + + Once peek() has been called, the original iterable will be modified if it + was an iterator (it will be advanced by 1); use the returned iterator for + an equivalent copy of the original iterable. + """ + it = iter(iterable) + first_element = next(it) + return first_element, chain([first_element], it) + def repeat_func(func, times=None, args=()): "equivalent to (func(*args) for i in xrange(times))." if times is None: @@ -11,6 +24,16 @@ def repeat_func(func, times=None, args=()): for i in xrange(times): yield func(*args) +def repeat_copy(object, times=None): + """Returns deep copies of `object` over and over again. Runs indefinitely + unless the `times` argument is specified.""" + if times is None: + while True: + yield deepcopy(object) + else: + for i in xrange(times): + yield object + def repeating_iterator(i, nreps): """Returns an iterator that emits each element of `i` multiple times specified by `nreps`. The length of this iterator is the lenght of `i` |