Split an iterator into chunks with `n` elements each. Warning: ``it`` must be an actual iterator, if you pass this a concrete sequence will get you repeating elements. So ``chunks(iter(range(1000)), 10)`` is fine, but ``chunks(range(1000), 10)`` is not. Exa
(it, n)
| 113 | |
| 114 | |
| 115 | def chunks(it, n): |
| 116 | """Split an iterator into chunks with `n` elements each. |
| 117 | |
| 118 | Warning: |
| 119 | ``it`` must be an actual iterator, if you pass this a |
| 120 | concrete sequence will get you repeating elements. |
| 121 | |
| 122 | So ``chunks(iter(range(1000)), 10)`` is fine, but |
| 123 | ``chunks(range(1000), 10)`` is not. |
| 124 | |
| 125 | Example: |
| 126 | # n == 2 |
| 127 | >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2) |
| 128 | >>> list(x) |
| 129 | [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]] |
| 130 | |
| 131 | # n == 3 |
| 132 | >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 3) |
| 133 | >>> list(x) |
| 134 | [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]] |
| 135 | """ |
| 136 | for item in it: |
| 137 | yield [item] + list(islice(it, n - 1)) |
| 138 | |
| 139 | |
| 140 | def padlist(container, size, default=None): |