0

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 like this:

desiredList = [['a', ['b']],
              ['a', ['b', 'c']],
              ['a', ['b', 'c', 'd']]]

Here is one of my attempts that comes close using lst1 + lst2 and list.append():

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

print(lst3)

#Output:
#[['a', 'b'],
#['a', 'b', 'c'],
#['a', 'b', 'c', 'd']]

Expanding on this, I thought another variation with theNew = new1.append(new2)would do the trick. But no:

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

    lst3.append(theNew)
print(lst3)

# Output:
[None, None, None]

And you'll get the same result with extend.

I guess this should be really easy, but I'm at a loss.

Thank you for any suggestions!

vestland
  • 55,229
  • 37
  • 187
  • 305

4 Answers4

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.

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
1

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)
1
from itertools import product

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

[lst1 + [new] for new in lst2]
>>>[['a', ['b']], ['a', ['b', 'c']], ['a', ['b', 'c', 'd']]]
Veera Balla Deva
  • 790
  • 6
  • 19
0

This might help

desiredlist = list(map(lambda y:[lst1,y],lst2))
Pawanvir singh
  • 373
  • 6
  • 17