Search code examples
pythonlistdivide

How to divide a list into n equal parts, python


Given (any) list of words lst I should divide it into 10 equal parts.

x = len(lst)/10

how to give these parts variable names?

In the output I need 10 variables (part1, part2... part10) with x number of words in it.


Solution

  • One-liner returning a list of lists, given a list and the chunk size:

    >>> lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
    

    Testing:

    >>> x = range(20, 36)
    >>> print x
    [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
    
    >>> lol(x, 4)
    [[20, 21, 22, 23], 
     [24, 25, 26, 27], 
     [28, 29, 30, 31], 
     [32, 33, 34, 35]]
    
    >>> lol(x, 7)
    [[20, 21, 22, 23, 24, 25, 26], 
     [27, 28, 29, 30, 31, 32, 33], 
     [34, 35]]
    

    Update:

    I think the question is really asking is a function which, given a list and a number, returns a list containing $(number) lists, with the items of the original list evenly distributed. So your example of lol(x, 7) should really return [[20,21,22], [23,24,25], [26,27], [28,29], [30,31], [32,33], [34,35]]. – markrian

    Well, in this case, you can try:

    def slice_list(input, size):
        input_size = len(input)
        slice_size = input_size / size
        remain = input_size % size
        result = []
        iterator = iter(input)
        for i in range(size):
            result.append([])
            for j in range(slice_size):
                result[i].append(iterator.next())
            if remain:
                result[i].append(iterator.next())
                remain -= 1
        return result
    

    I'm sure this can be improved but I'm feeling lazy. :-)

    >>> slice_list(x, 7)
    [[20, 21, 22], [23, 24, 25], 
     [26, 27], [28, 29], 
     [30, 31], [32, 33], 
     [34, 35]]