Python list transpose and fill

fill, list, python, transpose

Solution

You can repeat one element list forever:

uneven = [[1], [47, 17, 2, 3], [3], [12, 5, 75, 33]]

from itertools import repeat

print zip(*(repeat(*x) if len(x)==1 else x for x in uneven))

Problem

I have a list of lists such that the length of each inner list is either 1 or n (assume n > 1). ``` >>> uneven = [[1], [47, 17, 2, 3], [3], [12, 5, 75, 33]] ``` I want to transpose the list, but instead of truncating the longer list (as with `zip`) or filling the shorter lists with `None`, I want to fill the shorter lists with their own singular value. In other words, I'd like to get: ``` >>> [(1, 47, 3, 12), (1, 17, 3, 5), (1, 2, 3, 75), (1, 3, 3, 33)] ``` I can do this with a couple of iterations: ``` >>> maxlist = len(max(*uneven, key=len)) >>> maxlist 4 >>> from itertools import repeat >>> uneven2 = [x if len(x) == maxlist else repeat(x[0], maxlist) for x in uneven] >>> uneven2 [[1, 1, 1, 1], [47, 17, 2, 3], [3, 3, 3, 3], [12, 5, 75, 33]] >>> zip(*uneven2) [(1, 47, 3, 12), (1, 17, 3, 5), (1, 2, 3, 75), (1, 3, 3, 33)] ``` But is there a better approach? Do I really need to know `maxlist` in advance to accomplish this?

Original source