Split into chunks
You can split a list into chunks of a given size using zip
and iter
, as explained in this SO question.
>>> l=range(12)
>>> zip(*[iter(l)]*4)
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
Of course, substituting in l
as zip(*[iter(range(12))]*4)
gives the same result.
The 4
is the number of elements per chunk. If the length isn't a multiple of this, any elements in the remainder are not included. For example, l=range(13)
would give the same result.
The result is a list of tuples. If your input is a string and you want to produce a list of strings, you can do
>>> l="Code_golf"
>>> map(''.join,zip(*[iter(l)]*3))
['Cod', 'e_g', 'olf'] # Python 3 would give a map object
When the list l
is defined by a list comprehension, instead of converting to an iterable as iter(l)
, you can instead write it as a generator comprehension with (...)
instead of [...]
.
>>> l=(n for n in range(18)if n%3!=1)
>>> zip(*[l]*4)
[(0, 2, 3, 5), (6, 8, 9, 11), (12, 14, 15, 17)]
Note that thisThis consumes the generator, so l
will appear empty afterwards. Note as before that we can inline l
as zip(*[(n for n in range(18)if n%3!=1)]*4)
.