0

I would like to join the same index elements of many different lists of lists and obtaining a list of lists of the joined elements. The lists always have the same length. Here is an example much simpler to understand.

list1 = [[1, 0], [1, 0], [1, 0], [0, 1]]

list2 = [[2, 1], [2, 1], [1, 2], [3, 2]]

Results I would like to obtain:

LIST = [[1,0,2,1],[1,0,2,1],[1,0,1,2],[0,1,3,2]]

Any help would be really appreciated.

1
  • [sum(i, []) for i in zip(list1, list2)] Commented Mar 22, 2017 at 16:28

1 Answer 1

6

Use a list comprehension:

Result = [item1 + item2 for item1, item2 in zip(list1, list2)]

It's is the same thing as this:

Result = []
for item1, item2 in zip(list1, list2):
    Result.append(item1 + item2)

If you feel like this line is too long and a bit cumbersome, try this:

from operator import add

Result = list(map(add, zip(list1, list2)))

If you're using Python 2.x, you can safely get rid of the call to list in this example.

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

2 Comments

Thank you. Really appreciate, have a nice day.
@EsseTi, you're always welcome! Have a great day too!

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.