beginner to python here.
I have 2 nested lists that I want to merge:
list1 = ['a',
(b, c),
(d, e),
(f, g, h) ]
list2 = [(p,q),
(r, s),
(t),
(u, v, w) ]
the output I am looking for is:
list3 = [(a, p, q),
(b, c, r, s),
(d, e, t),
(f, g, h, u, v, w) ]
Can this be done without any external libraries? note: len(list1) = len(list2)
First, flatten the nested lists. Take Intersection using filter() and save it to 'lst3'. Now find elements either not in lst1 or in lst2, and save them to 'temp'. Finally, append 'temp' to 'lst3'.
One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list. It doesn't return a new list of items. Instead, it modifies the original list by adding the item to the end of the list.
Use the power of the zip
function and list comprehensions:
list1 = [('a', ),
('b', 'c'),
('d', 'e'),
('f', 'g', 'h') ]
list2 = [('p', 'q'),
('r', 's'),
('t', ),
('u', 'v', 'w') ]
print [a + b for a, b in zip(list1, list2)]
from operator import add
list3 = map(add, list1, list2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With