Search code examples
pythonlistmathrandom

Best way to split a list into randomly sized chunks?


I have a list of numbers such as

[5000, 5000, 5000, 5000, 5000, 5000]

I need to create a function that turns that list into a list of randomly sized smaller lists, such as :

[[5000, 5000], [5000, 5000, 5000], [5000]]

What's the best way to do this in python?


Solution

  • from itertools import islice
    from random import randint
    
    def random_chunk(li, min_chunk=1, max_chunk=3):
        it = iter(li)
        while True:
            nxt = list(islice(it,randint(min_chunk,max_chunk)))
            if nxt:
                yield nxt
            else:
                break
    

    demo:

    li = [5000, 5000, 5000, 5000, 5000, 5000]
    
    list(random_chunk(li))
    Out[45]: [[5000, 5000, 5000], [5000], [5000, 5000]]
    

    This results in a (ignoring the last chunk) uniform distribution of chunk sizes between min_chunk and max_chunk, inclusively.