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

Advertisements

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.

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

Leave a ReplyCancel reply