To divide a list into equal sized pieces in Python

Asked 2 years ago, Updated 2 years ago, 74 views

You want to divide a list of arbitrary lengths into pieces of the same size. Of course, there are clear ways of putting two counters and a list, and every time a second list is filled, there are ways of adding them to the first list, but this seems to be a potentially inefficient way.

Does anyone have a good solution (e.g., using a generator) to make a list of any length possible?

I'm looking forward to working this way.

l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]

I looked for something useful in itertools but I couldn't find it.

split chunks python list

2022-09-22 12:36

1 Answers

This is a generator that shields the divided pieces as you want.

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i+n]
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
 [70, 71, 72, 73, 74]]

If you are using Python 2, you should use xrange() instead of range()

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

There is also a way to use list compression as shown below without using the function.

Python 3:

[l[i:i+n] for i in range(0, len(l), n)]
[l[i:i+n] for i in xrange(0, len(l), n)]


2022-09-22 12:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.