Fox Fox - 2 months ago 5
Python Question

How to append lists of list into one list

Mylists = [['A B','A B C','A B C D'],['C','D E F','A B']]

How can I get a list like: myli = [['A','B','A','B','C','A','B','C','D'],['C','D','E','F','A','B']]

Here is my code:

x = []
myli = []

for item in Mylists:
for i in range(len(item)):
x.extend(item[i].split())
myli.append(x)

Answer

You need to initialize x inside the outer forloop.

Your code

Mylists = [['A B','A B C','A B C D'],['C','D E F','A B']]
x = []
myli = []

for item in Mylists:
    for i in range(len(item)):
        # BUG: since x is not reinitialized, it contains the same old
        # memory address that was appended to myli
        # extending x means you are modifying the x that you previously appended to myli
        # infact, every appended x is the same x !
        x.extend(item[i].split())

    # appending the same old x, which will inevitably be modified
    # in the next iteration
    myli.append(x)

Correction

Mylists = [['A B','A B C','A B C D'],['C','D E F','A B']]
myli = []

for item in Mylists:
    x = [] # reinitialize x
    for i in range(len(item)):
        x.extend(item[i].split())
    myli.append(x)
Comments