By user248237


2010-01-25 03:19:28 8 Comments

What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in one part, and the other should have 4 elements.

I'm looking for something like even_split(L, n) that breaks L into n parts.

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

The code above gives chunks of 3, rather than 3 chunks. I could simply transpose (iterate over this and take the first element of each column, call that part one, then take the second and put it in part two, etc), but that destroys the ordering of the items.

30 comments

@Solal Baudoin 2020-07-05 23:38:48

def chunk_array(array : List, n: int) -> List[List]:
    chunk_size = len(array) // n 
    chunks = []
    i = 0
    while i < len(array):
        # if less than chunk_size left add the remainder to last element
        if len(array) - (i + chunk_size + 1) < 0:
            chunks[-1].append(*array[i:i + chunk_size])
            break
        else:
            chunks.append(array[i:i + chunk_size])
            i += chunk_size
    return chunks

here's my version (inspired from Max's)

@Bbake Waikhom 2020-06-26 11:08:43

1>

import numpy as np

data # your array

total_length = len(data)
separate = 10
sub_array_size = total_length // separate
safe_separate = sub_array_size * separate

splited_lists = np.split(np.array(data[:safe_separate]), separate)
splited_lists[separate - 1] = np.concatenate(splited_lists[separate - 1], 
np.array(data[safe_separate:total_length]))

splited_lists # your output

2>

splited_lists = np.array_split(np.array(data), separate)

@Ali Sajjad 2020-06-04 11:23:18

Let's say you want to split a list [1, 2, 3, 4, 5, 6, 7, 8] into 3 element lists

like [[1,2,3], [4, 5, 6], [7, 8]], where if the last remaining elements left are less than 3, they are grouped together.

my_list = [1, 2, 3, 4, 5, 6, 7, 8]
my_list2 = [my_list[i:i+3] for i in range(0, len(my_list), 3)]
print(my_list2)

Output: [[1,2,3], [4, 5, 6], [7, 8]]

Where length of one part is 3. Replace 3 with your own chunk size.

@tixxit 2010-01-25 21:48:42

You can write it fairly simply as a list generator:

def split(a, n):
    k, m = divmod(len(a), n)
    return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n))

Example:

>>> list(split(range(11), 3))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]

@abanana 2017-02-23 17:28:37

Insert n = min(n, len(a)) # don't create empty buckets on line 1 to avoid creating empty buckets in scenarios like list(split(range(X, Y))) where X < Y

@abanana 2017-02-24 11:50:44

Seeing as I can't edit my comment -- I should add that my previous amendment could possibly raise a division by zero error if the list is empty, so that needs to either be controlled externally or added to the solution.

@avishayp 2017-05-17 07:26:56

Out of N answer on SO, this is the only one that has passed all my tests. gj!

@LookAheadAtYourTypes 2017-11-04 14:20:38

stackoverflow.com/a/37414115/210971 uses the same method, but works also for empty list and 0 split counter.

@haraprasadj 2019-04-22 04:07:41

Beautiful! Also, n can be made to work as batch_size by swapping k and n in the return statement :)

@FlyingZebra1 2019-06-19 00:25:27

this solution is better than the accepted answer, since it splits list into equal-ish chunks for all chunks. the accepted answer has the potential to have 1 item in its last list.

@wim 2020-04-03 00:06:23

@avishayp Can you share those tests in a gist or pastebin?

@Max Shawabkeh 2010-01-25 03:27:31

This code is broken due to rounding errors. Do not use it!!!

assert len(chunkIt([1,2,3], 10)) == 10  # fails

Here's one that could work:

def chunkIt(seq, num):
    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg

    return out

Testing:

>>> chunkIt(range(10), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
>>> chunkIt(range(11), 3)
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10]]
>>> chunkIt(range(12), 3)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

@nopper 2013-10-07 16:01:57

Your example won't work for >>> chunkIt(range(8), 6) => [[0], [1], [2, 3], [4], [5], [6], [7]]

@paulie4 2013-10-10 15:18:02

@nopper, I added an "if num == 1:" conditional to handle that edge case.

@wim 2017-05-16 01:58:52

New visitors: please don't use or upvote this code, it's broken. e.g. chunkIt(range(10), 9) should return 9 parts, but it doesn't.

@Sanath Kumar 2017-11-06 23:47:25

@wim it seems like it is returning the correct values. Are you still facing any issues with this implementation?

@Rodrigo Ney 2017-11-08 18:12:50

I added if num > len(seq): num = len(seq) at the start of the function.

@conchoecia 2018-02-21 23:08:33

This comment thread is really confusing as the answer has been edited several times. Is this a good answer? Not a good answer?

@wim 2018-05-10 13:50:51

@conchoecia Not a good answer, keep scrolling down. This was just edited once so far, and it was only a trivial edit (2 space indent changed to 4). Unfortunately the OP "user248237dfsf" hasn't been seen on the site for over 3 years, so there is little hope of getting the accepted answer changed.

@wim 2017-03-30 00:22:34

This is the raison d'être for numpy.array_split*:

>>> import numpy as np
>>> print(*np.array_split(range(10), 3))
[0 1 2 3] [4 5 6] [7 8 9]
>>> print(*np.array_split(range(10), 4))
[0 1 2] [3 4 5] [6 7] [8 9]
>>> print(*np.array_split(range(10), 5))
[0 1] [2 3] [4 5] [6 7] [8 9]

*credit to Zero Piraeus in room 6

@yuqli 2019-05-01 02:46:20

What's the * in print for?

@Robert Lugg 2019-06-26 21:01:51

Hey @yuqli, It converts a list of something into individual arguments to a function. try print(L) and `print(*L). Also see stackoverflow.com/a/36908/2184122 or search for "python use of asterisk".

@Ghanem 2019-10-18 17:11:59

If you don't mind that the order will be changed, I recommend you to use @job solution, otherwise, you can use this:

def chunkIt(seq, num):
    steps = int(len(seq) / float(num))
    out = []
    last = 0.0

    while last < len(seq):
        if len(seq) - (last + steps) < steps:
            until = len(seq)
            steps = len(seq) - last
        else:
            until = int(last + steps)
        out.append(seq[int(last): until])
        last += steps
return out

@emremrah 2019-09-06 08:10:12

def evenly(l, n):
    len_ = len(l)
    split_size = len_ // n
    split_size = n if not split_size else split_size
    offsets = [i for i in range(0, len_, split_size)]
    return [l[offset:offset + split_size] for offset in offsets]

Example:

l = [a for a in range(97)] should be consist of 10 parts, each have 9 elements except the last one.

Output:

[[0, 1, 2, 3, 4, 5, 6, 7, 8],
 [9, 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, 75, 76, 77, 78, 79, 80],
 [81, 82, 83, 84, 85, 86, 87, 88, 89],
 [90, 91, 92, 93, 94, 95, 96]]

@Ângelo Polotto 2019-08-29 15:11:28

I tried most part of solutions, but they didn't work for my case, so I make a new function that work for most of cases and for any type of array:

import math

def chunkIt(seq, num):
    seqLen = len(seq)
    total_chunks = math.ceil(seqLen / num)
    items_per_chunk = num
    out = []
    last = 0

    while last < seqLen:
        out.append(seq[last:(last + items_per_chunk)])
        last += items_per_chunk

    return out

@Anthony Manning-Franklin 2019-07-16 08:42:04

This one provides chunks of length <= n, >= 0

def

 chunkify(lst, n):
    num_chunks = int(math.ceil(len(lst) / float(n))) if n < len(lst) else 1
    return [lst[n*i:n*(i+1)] for i in range(num_chunks)]

for example

>>> chunkify(range(11), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
>>> chunkify(range(11), 8)
[[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10]]

@grafi71 2019-07-13 18:37:03

this code works for me (Python3-compatible):

def chunkify(tab, num):
    return [tab[i*num: i*num+num] for i in range(len(tab)//num+(1 if len(tab)%num else 0))]

example (for bytearray type, but it works for lists as well):

b = bytearray(b'\x01\x02\x03\x04\x05\x06\x07\x08')
>>> chunkify(b,3)
[bytearray(b'\x01\x02\x03'), bytearray(b'\x04\x05\x06'), bytearray(b'\x07\x08')]
>>> chunkify(b,4)
[bytearray(b'\x01\x02\x03\x04'), bytearray(b'\x05\x06\x07\x08')]

@Cipher.Chen 2019-03-25 02:28:41

I've written code in this case myself:

def chunk_ports(port_start, port_end, portions):
    if port_end < port_start:
        return None

    total = port_end - port_start + 1

    fractions = int(math.floor(float(total) / portions))

    results = []

    # No enough to chuck.
    if fractions < 1:
        return None

    # Reverse, so any additional items would be in the first range.
    _e = port_end
    for i in range(portions, 0, -1):
        print "i", i

        if i == 1:
            _s = port_start
        else:
            _s = _e - fractions + 1

        results.append((_s, _e))

        _e = _s - 1

    results.reverse()

    return results

divide_ports(1, 10, 9) would return

[(1, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)]

@Danil 2018-10-03 16:36:30

say you want to split into 5 parts:

p1, p2, p3, p4, p5 = np.split(df, 5)

@NickD 2018-10-03 20:22:17

This does not provide an answer to the question, e.g. how would you write it if you don't know in advance that you want to split it in five pieces. Also, you are (I'm guessing) assuming numpy and maybe a pandas dataframe. The OP is asking about a generic list.

@swateek 2018-09-05 04:28:24

#!/usr/bin/python


first_names = ['Steve', 'Jane', 'Sara', 'Mary','Jack','Bob', 'Bily', 'Boni', 'Chris','Sori', 'Will', 'Won','Li']

def chunks(l, n):
for i in range(0, len(l), n):
    # Create an index range for l of n items:
    yield l[i:i+n]

result = list(chunks(first_names, 5))
print result

Picked from this link, and this was what helped me. I had a pre-defined list.

@pylang 2018-07-16 20:41:47

See more_itertools.divide:

n = 2

[list(x) for x in mit.divide(n, range(5, 11))]
# [[5, 6, 7], [8, 9, 10]]

[list(x) for x in mit.divide(n, range(5, 12))]
# [[5, 6, 7, 8], [9, 10, 11]]

Install via > pip install more_itertools.

@Chłop Z Lasu 2018-02-07 18:12:38

My solution, easy to understand

def split_list(lst, n):
    splitted = []
    for i in reversed(range(1, n + 1)):
        split_point = len(lst)//i
        splitted.append(lst[:split_point])
        lst = lst[split_point:]
    return splitted

And shortest one-liner on this page(written by my girl)

def split(l, n):
    return [l[int(i*len(l)/n):int((i+1)*len(l)/n-1)] for i in range(n)]

@Paulo Freitas 2018-06-12 22:08:33

FYI: Your one-liner is broken, yields wrong results. The other one works beautifully.

@bitagoras 2017-11-20 16:33:33

This will do the split by a single expression:

>>> myList = range(18)
>>> parts = 5
>>> [myList[(i*len(myList))//parts:((i+1)*len(myList))//parts] for i in range(parts)]
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9], [10, 11, 12, 13], [14, 15, 16, 17]]

The list in this example has the size 18 and is divided into 5 parts. The size of the parts differs in no more than one element.

@job 2010-01-25 22:18:16

As long as you don't want anything silly like continuous chunks:

>>> def chunkify(lst,n):
...     return [lst[i::n] for i in xrange(n)]
... 
>>> chunkify(range(13), 3)
[[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]]

@tixxit 2010-01-26 14:39:43

I wouldn't say continuous chunks are silly. Perhaps you'd like to keep the chunks sorted (ie. chunk[0] < chunk[1]), for instance.

@job 2010-01-26 15:49:16

I was kidding. But if you really didn't care, this way with list comprehension is nice and concise.

@smci 2014-09-12 03:30:22

This is subscripting with a stride of n

@gens 2017-04-13 18:40:18

sending this output into 'zip' gives you your ordered list: zip(*chunkify(range(13), 3)) results in [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]

@s7anley 2017-04-19 03:47:10

This solutions works fine, until you need order of list the stay same.

@Vedran Šego 2018-01-18 15:21:24

Along with @gens comment, this is brilliant!

@Adirio 2018-05-31 09:22:16

@gens comment looses uneven elements (12)

@gens 2018-05-31 20:16:45

@Adirio use itertools.zip_longest to end up with an extra tuple with the 12 in it

@gens 2018-05-31 20:26:03

another way in py2 is to map with None: map(None, *chunkify(range(13), 3)) which gives [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, None, None)]

@Ghanem 2019-10-18 17:00:44

@gens , nope! then it deletes the last items. try: s = [0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14] with 4 chunks .. from 12, 13, 14 will be discarded.

@PM 2Ring 2017-03-30 09:51:35

Here's a generator that can handle any positive (integer) number of chunks. If the number of chunks is greater than the input list length some chunks will be empty. This algorithm alternates between short and long chunks rather than segregating them.

I've also included some code for testing the ragged_chunks function.

''' Split a list into "ragged" chunks

    The size of each chunk is either the floor or ceiling of len(seq) / chunks

    chunks can be > len(seq), in which case there will be empty chunks

    Written by PM 2Ring 2017.03.30
'''

def ragged_chunks(seq, chunks):
    size = len(seq)
    start = 0
    for i in range(1, chunks + 1):
        stop = i * size // chunks
        yield seq[start:stop]
        start = stop

# test

def test_ragged_chunks(maxsize):
    for size in range(0, maxsize):
        seq = list(range(size))
        for chunks in range(1, size + 1):
            minwidth = size // chunks
            #ceiling division
            maxwidth = -(-size // chunks)
            a = list(ragged_chunks(seq, chunks))
            sizes = [len(u) for u in a]
            deltas = all(minwidth <= u <= maxwidth for u in sizes)
            assert all((sum(a, []) == seq, sum(sizes) == size, deltas))
    return True

if test_ragged_chunks(100):
    print('ok')

We can make this slightly more efficient by exporting the multiplication into the range call, but I think the previous version is more readable (and DRYer).

def ragged_chunks(seq, chunks):
    size = len(seq)
    start = 0
    for i in range(size, size * chunks + 1, size):
        stop = i // chunks
        yield seq[start:stop]
        start = stop

@leotrubach 2014-09-24 15:55:54

Here is my solution:

def chunks(l, amount):
    if amount < 1:
        raise ValueError('amount must be positive integer')
    chunk_len = len(l) // amount
    leap_parts = len(l) % amount
    remainder = amount // 2  # make it symmetrical
    i = 0
    while i < len(l):
        remainder += leap_parts
        end_index = i + chunk_len
        if remainder >= amount:
            remainder -= amount
            end_index += 1
        yield l[i:end_index]
        i = end_index

Produces

    >>> list(chunks([1, 2, 3, 4, 5, 6, 7], 3))
    [[1, 2], [3, 4, 5], [6, 7]]

@Carlos del Ojo 2015-02-18 11:51:38

You could also use:

split=lambda x,n: x if not x else [x[:n]]+[split([] if not -(len(x)-n) else x[-(len(x)-n):],n)][0]

split([1,2,3,4,5,6,7,8,9],2)

[[1, 2], [3, 4], [5, 6], [7, 8], [9]]

@galliwuzz 2016-07-20 13:04:20

Rounding the linspace and using it as an index is an easier solution than what amit12690 proposes.

function chunks=chunkit(array,num)

index = round(linspace(0,size(array,2),num+1));

chunks = cell(1,num);

for x = 1:num
chunks{x} = array(:,index(x)+1:index(x+1));
end
end

@MaPePeR 2016-05-24 12:48:57

If you divide n elements into roughly k chunks you can make n % k chunks 1 element bigger than the other chunks to distribute the extra elements.

The following code will give you the length for the chunks:

[(n // k) + (1 if i < (n % k) else 0) for i in range(k)]

Example: n=11, k=3 results in [4, 4, 3]

You can then easily calculate the start indizes for the chunks:

[i * (n // k) + min(i, n % k) for i in range(k)]

Example: n=11, k=3 results in [0, 4, 8]

Using the i+1th chunk as the boundary we get that the ith chunk of list l with len n is

l[i * (n // k) + min(i, n % k):(i+1) * (n // k) + min(i+1, n % k)]

As a final step create a list from all the chunks using list comprehension:

[l[i * (n // k) + min(i, n % k):(i+1) * (n // k) + min(i+1, n % k)] for i in range(k)]

Example: n=11, k=3, l=range(n) results in [range(0, 4), range(4, 8), range(8, 11)]

@liscju 2015-11-14 15:06:48

Using list comprehension:

def divide_list_to_chunks(list_, n):
    return [list_[start::n] for start in range(n)]

@SuperBiasedMan 2015-11-14 15:25:44

This doesn't address the issue of making all the chunks even.

@amit12690 2015-04-21 05:25:40

Implementation using numpy.linspace method.

Just specify the number of parts you want the array to be divided in to.The divisions will be of nearly equal size.

Example :

import numpy as np   
a=np.arange(10)
print "Input array:",a 
parts=3
i=np.linspace(np.min(a),np.max(a)+1,parts+1)
i=np.array(i,dtype='uint16') # Indices should be floats
split_arr=[]
for ind in range(i.size-1):
    split_arr.append(a[i[ind]:i[ind+1]]
print "Array split in to %d parts : "%(parts),split_arr

Gives :

Input array: [0 1 2 3 4 5 6 7 8 9]
Array split in to 3 parts :  [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8, 9])]

@Ilya Tuvschev 2014-06-13 14:37:56

The same as job's answer, but takes into account lists with size smaller than the number of chuncks.

def chunkify(lst,n):
    [ lst[i::n] for i in xrange(n if n < len(lst) else len(lst)) ]

if n (number of chunks) is 7 and lst (the list to divide) is [1, 2, 3] the chunks are [[0], [1], [2]] instead of [[0], [1], [2], [], [], [], []]

@jreyes 2013-09-22 16:54:11

Here's another variant that spreads the "remaining" elements evenly among all the chunks, one at a time until there are none left. In this implementation, the larger chunks occur at the beginning the process.

def chunks(l, k):
  """ Yield k successive chunks from l."""
  if k < 1:
    yield []
    raise StopIteration
  n = len(l)
  avg = n/k
  remainders = n % k
  start, end = 0, avg
  while start < n:
    if remainders > 0:
      end = end + 1
      remainders = remainders - 1
    yield l[start:end]
    start, end = end, end+avg

For example, generate 4 chunks from a list of 14 elements:

>>> list(chunks(range(14), 4))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10], [11, 12, 13]]
>>> map(len, list(chunks(range(14), 4)))
[4, 4, 3, 3]

@Akavall 2012-03-21 04:05:55

Another way would be something like this, the idea here is to use grouper, but get rid of None. In this case we'll have all 'small_parts' formed from elements at the first part of the list, and 'larger_parts' from the later part of the list. Length of 'larger parts' is len(small_parts) + 1. We need to consider x as two different sub-parts.

from itertools import izip_longest

import numpy as np

def grouper(n, iterable, fillvalue=None): # This is grouper from itertools
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

def another_chunk(x,num):
    extra_ele = len(x)%num #gives number of parts that will have an extra element 
    small_part = int(np.floor(len(x)/num)) #gives number of elements in a small part

    new_x = list(grouper(small_part,x[:small_part*(num-extra_ele)]))
    new_x.extend(list(grouper(small_part+1,x[small_part*(num-extra_ele):])))

    return new_x

The way I have it set up returns a list of tuples:

>>> x = range(14)
>>> another_chunk(x,3)
[(0, 1, 2, 3), (4, 5, 6, 7, 8), (9, 10, 11, 12, 13)]
>>> another_chunk(x,4)
[(0, 1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13)]
>>> another_chunk(x,5)
[(0, 1), (2, 3, 4), (5, 6, 7), (8, 9, 10), (11, 12, 13)]
>>> 

@dalloliogm 2010-02-10 09:19:37

Have a look at numpy.split:

>>> a = numpy.array([1,2,3,4])
>>> numpy.split(a, 2)
[array([1, 2]), array([3, 4])]

@Yariv 2013-03-09 10:38:53

And numpy.array_split() is even more adequate because it roughly splits.

@Dan 2013-07-26 02:32:19

This doesn't work if the array size isn't divisible by the number of splits.

@Chłop Z Lasu 2018-02-07 18:07:41

This is wrong answer, your solution returns list of ndarrays, not list of lists

@paxdiablo 2010-01-25 03:30:11

Changing the code to yield n chunks rather than chunks of n:

def chunks(l, n):
    """ Yield n successive chunks from l.
    """
    newn = int(len(l) / n)
    for i in xrange(0, n-1):
        yield l[i*newn:i*newn+newn]
    yield l[n*newn-newn:]

l = range(56)
three_chunks = chunks (l, 3)
print three_chunks.next()
print three_chunks.next()
print three_chunks.next()

which gives:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 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]

This will assign the extra elements to the final group which is not perfect but well within your specification of "roughly N equal parts" :-) By that, I mean 56 elements would be better as (19,19,18) whereas this gives (18,18,20).

You can get the more balanced output with the following code:

#!/usr/bin/python
def chunks(l, n):
    """ Yield n successive chunks from l.
    """
    newn = int(1.0 * len(l) / n + 0.5)
    for i in xrange(0, n-1):
        yield l[i*newn:i*newn+newn]
    yield l[n*newn-newn:]

l = range(56)
three_chunks = chunks (l, 3)
print three_chunks.next()
print three_chunks.next()
print three_chunks.next()

which outputs:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 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]

@user248237 2010-01-25 03:36:16

this gives me a strange result. for p in chunks(range(54), 3): print len(p) returns 18, 18, 51...

@paxdiablo 2010-01-25 03:37:38

Fixed, that, it was the final yield.

@Jakob Kroeker 2013-07-19 16:14:20

see also a solition at link

@mVChr 2014-08-18 20:49:21

This is the most useful answer for practical considerations. Thanks!

@synaptik 2015-06-19 21:47:14

When I use this, doing for x in chunks(mylist,num): print x, I get the desired chunks, but between them I get an empty list. Any idea why? That is, I get lots of [], one after each chunk.

@Andomar 2016-05-02 09:10:21

Useful, nitpick: fails if n > len(l), added a special case for that, if len(l) < n: return [[x] for x in l]

Related Questions

Sponsored Content

42 Answered Questions

[SOLVED] How to make a flat list out of list of lists?

64 Answered Questions

[SOLVED] How do you split a list into evenly sized chunks?

22 Answered Questions

24 Answered Questions

[SOLVED] How do I concatenate two lists in Python?

12 Answered Questions

[SOLVED] Getting the last element of a list

  • 2009-05-30 19:28:53
  • Janusz
  • 2191577 View
  • 2125 Score
  • 12 Answer
  • Tags:   python list indexing

30 Answered Questions

[SOLVED] Finding the index of an item in a list

  • 2008-10-07 01:39:38
  • Eugene M
  • 3999572 View
  • 3269 Score
  • 30 Answer
  • Tags:   python list indexing

27 Answered Questions

[SOLVED] How do I check if a list is empty?

  • 2008-09-10 06:20:11
  • Ray
  • 2987189 View
  • 3234 Score
  • 27 Answer
  • Tags:   python list

20 Answered Questions

36 Answered Questions

[SOLVED] What is the most "pythonic" way to iterate over a list in chunks?

21 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 4545244 View
  • 3472 Score
  • 21 Answer
  • Tags:   python directory

Sponsored Content