Advance *iterable* by *n* steps. If *n* is ``None``, consume it entirely. Efficiently exhausts an iterator without returning values. Defaults to consuming the whole iterator, but an optional second argument may be provided to limit consumption. >>> i = (x for x in range(10))
(iterator, n=None)
| 45 | |
| 46 | # from more_itertools v9.0.0 |
| 47 | def consume(iterator, n=None): |
| 48 | """Advance *iterable* by *n* steps. If *n* is ``None``, consume it |
| 49 | entirely. |
| 50 | Efficiently exhausts an iterator without returning values. Defaults to |
| 51 | consuming the whole iterator, but an optional second argument may be |
| 52 | provided to limit consumption. |
| 53 | >>> i = (x for x in range(10)) |
| 54 | >>> next(i) |
| 55 | 0 |
| 56 | >>> consume(i, 3) |
| 57 | >>> next(i) |
| 58 | 4 |
| 59 | >>> consume(i) |
| 60 | >>> next(i) |
| 61 | Traceback (most recent call last): |
| 62 | File "<stdin>", line 1, in <module> |
| 63 | StopIteration |
| 64 | If the iterator has fewer items remaining than the provided limit, the |
| 65 | whole iterator will be consumed. |
| 66 | >>> i = (x for x in range(3)) |
| 67 | >>> consume(i, 5) |
| 68 | >>> next(i) |
| 69 | Traceback (most recent call last): |
| 70 | File "<stdin>", line 1, in <module> |
| 71 | StopIteration |
| 72 | """ |
| 73 | # Use functions that consume iterators at C speed. |
| 74 | if n is None: |
| 75 | # feed the entire iterator into a zero-length deque |
| 76 | deque(iterator, maxlen=0) |
| 77 | else: |
| 78 | # advance to the empty slice starting at position n |
| 79 | next(islice(iterator, n, n), None) |
no outgoing calls
searching dependent graphs…