How to group elements in python by n elements [duplicate]

Well, the brute force answer is:

subList = [theList[n:n+N] for n in range(0, len(theList), N)]

where N is the group size (3 in your case):

>>> theList = list(range(10))
>>> N = 3
>>> subList = [theList[n:n+N] for n in range(0, len(theList), N)]
>>> subList
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

If you want a fill value, you can do this right before the list comprehension:

tempList = theList + [fill] * N
subList = [tempList[n:n+N] for n in range(0, len(theList), N)]

Example:

>>> fill = 99
>>> tempList = theList + [fill] * N
>>> subList = [tempList[n:n+N] for n in range(0, len(theList), N)]
>>> subList
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 99, 99]]

Leave a Comment

tech