I have the following lists:
list_1 = [['name1', '001'], ['name2', '001'], ...]
list_2 = [['other1', '003'], ['other2', '005'], ...]
I want to combine them to the below, while stopping once either of the lists are exhausted (as per zip()
):
combined_list = [['name1', '001', 'other1', '003'], ['name2', '001', 'other2', '005']]
I have tried zip()
but this yields a tuple of two lists for each intended combined child list.
Is there a way to achieve this succinctly (without further looping after a zip()
)?
CodePudding user response:
What code have you tried? I suspect you have an issue with how you've called zip()
.
This will add both lists together at each index, using zip()
:
list_1 = [['name1', '001'], ['name2', '001']]
list_2 = [['other1', '003'], ['other2', '005']]
combined_list = [x y for x, y in zip(list_1, list_2)]
print(combined_list)
[['name1', '001', 'other1', '003'], ['name2', '001', 'other2', '005']]
CodePudding user response:
Another way (Try it online!):
from operator import concat
combined_list = list(map(concat, list_1, list_2))