Skip to content Skip to sidebar Skip to footer

How To Merge Two Lists Into A List Of Multiple Lists?

Given two lists lst1 and lst2: lst1 = ['a'] lst2 = [['b'], ['b', 'c'], ['b', 'c', 'd']] I'd like to merge them into a list of multiple lists with a desired output

Solution 1:

You could achieve your desired output with itertools.zip_longest with a fillvalue:

>>> from itertools import zip_longest
>>> list(zip_longest(lst1, lst2, fillvalue=lst1[0]))
[('a', ['b']), ('a', ['b', 'c']), ('a', ['b', 'c', 'd'])]

Or if you need a list of lists:

>>> [list(item) for item in zip_longest(lst1, lst2, fillvalue=lst1[0])]
[['a', ['b']], ['a', ['b', 'c']], ['a', ['b', 'c', 'd']]]

Note this assumes that lst1 always contains a single element as in your example.

Solution 2:

Or you can use use append, but you need to create new copy of the lst1:

lst3 = []
for elem in lst2:
    theNew = lst1[:]
    theNew.append(new2)
    lst3.append(theNew)
print(lst3)

Solution 3:

fromitertoolsimportproductlist(product(lst1,lst2))
>>>[('a', ['b']), ('a', ['b', 'c']), ('a', ['b', 'c', 'd'])]

[lst1 + [new]fornewinlst2]
>>>[['a', ['b']], ['a', ['b', 'c']], ['a', ['b', 'c', 'd']]]

Solution 4:

This might help

desiredlist = list(map(lambda y:[lst1,y],lst2))

Post a Comment for "How To Merge Two Lists Into A List Of Multiple Lists?"