The most pythonic way to cut a Python list every 100 elements

I have a list containing many items. I want to cut every 100 elements into a list of several lists.

For instance:

>>> a = range(256)
>>> b = slice(a, 100)

bshould be [[0,1,2,...99],[100,101,102,...199],[200,201,...,255]].

What is the most pythonic and elegant way to do this?

+2
source share
1 answer

This should do the trick:

[a[i:i+100] for i in range(0, len(a), 100)]

rangeaccepts an optional third argumentstep , so it range(0, n, 100)will 0, 100, 200, ....

+11
source

Source: https://habr.com/ru/post/1771586/


All Articles