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!

1
  • 1
    list.append() is in-place and returns None so never assign to it with = Commented Feb 6, 2018 at 11:05

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Or just: [[*lst1, other] for other in lst2]
@Jon Clements. As far as I can tell, this has to be the most elegant solution. Would you like to write it up as an answer?
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)

Comments

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

Comments

0

This might help

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.