Merge python lists of different lengths

Viewed 7464

I am attempting to merge two python lists, where their values at a given index will form a list (element) in a new list. For example:

merge_lists([1,2,3,4], [1,5]) = [[1,1], [2,5], [3], [4]]

I could iterate on this function to combine ever more lists. What is the most efficient way to accomplish this?

Edit (part 2)

Upon testing the answer I had previously selected, I realized I had additional criteria and a more general problem. I would also like to combine lists containing lists or values. For example:

merge_lists([[1,2],[1]] , [3,4]) = [[1,2,3], [1,4]]

The answers currently provided generate lists of higher dimensions in cases like this.

4 Answers

Another way using zip_longest and chain from itertools:

import itertools
[i for i in list(itertools.chain(*itertools.zip_longest(list1, list2, list3))) if i is not None]

or in 2 lines (more readable):

merged_list = list(itertools.chain(*itertools.zip_longest(a, b, c)))
merged_list = [i for i in merged_list if i is not None]
Related