[Python-ideas] Add a .chunks() method to sequences

Nick Coghlan ncoghlan at gmail.com
Tue May 2 10:09:21 EDT 2017

On 2 May 2017 at 22:10,  <robert.hoelzl at posteo.de> wrote:
> Steven D’Aprano was giving me an idea (in the bytes.hex delimiter
> discussion):
> I had very often the use case that I want to split sequences into
> subsequences of same size.
> How about adding a chunks() and rchunks() function to sequences:
> [1,2,3,4,5,6,7].chunks(3) => [[1,2,3], [4,5,6], [7]]
> "1234“.chunks(2) => [“12“, “34“]
> (this could then be used to emulate stevens proposal: “
> “.join(“1234567“.chunks(2)) => “12 34 56 7“)

While there may be a case for a "splitslices()" method on strings for
text formatting purposes, that case is weaker for generic sequences -
we don't offer general purpose equivalents to split() or partition()

That said, the possibility of a sequence or container focused
counterpart to "itertools" has come up before, and it's conceivable
such an algorithm might find a home there.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list