Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Joining several element inside a list in a list, in python

Say there is a list:

List = [["A", "A", "A", "A", "B", "B", "B", "B"], 
["C", "C", "D", "D", "C", "C", "D", "D"], 
["E", "F", "E", "F", "E", "F", "E", "F"]]

i want to join each of the first, second, and third element to a new list, so the new list will look like this:

NewList = ["ACE", "ACF", "ADE", "ADF", "BCE", "BCF", "BDE", "BDF"]

The problem is, it’ll only work if I know how much list are in the "parent" list, in this case it has 3 element.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want them to join the like this

for i in range(8):
    NewList.append(List[0][i] + List[1][i] + List[2][1] + ... List[n][i]

>Solution :

The zip() function is what you need

It allows two equal-size lists to be "zipped up" with element 0 of the first list being brought in alongside element 0 of the second, element 1 with element 1, etc.

It also works with multiple lists, more than 2.

You can use the * operator usefully here

It extracts the various separate lists from List

A list comprehension can do all your work for you

@python_user shows a brilliant solution above:

NewList = [''.join(one_list) for one_list in zip(*List)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading