pythoniterable-unpacking

Unpacking into several lists of fixed length


I have a list of data (of varying type) that I need to process. It has fixed length and I know which index holds what data, so currently I do something like

for x in data[:13]:
  do_stuff(x)
for x in data[13:21]:
  do_other_stuff(x)
...

I know I can split the data manually like

list1 = data[:13]
list2 = data[13:21]
...

but I was wondering if there was a way to do it in one line similar to the normal list unpacking, maybe like

*list1[13], *list2[8], *rest = data

Solution

  • There isn't a way to do what you want directly via slicing, but you could write a function that does this:

    def split_list(src, split_sizes):
        ret_lists = []
        last_split = 0
        for s in split_sizes:
            next_split = s + last_split
            ret_lists.append(src[last_split:next_split])
            last_split = next_split
    
        ret_lists.append(src[last_split:])
        return ret_lists
    

    Then, pass your expected sizes to this function as a list or tuple:

    list1, list2, rest = split_list(data, [13, 8])
    

    With example data:

    data = list(range(25))
    

    This function call gives the expected splits:

    [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]