How to append lists of list into one list
<p>Mylists = [['A B','A B C','A B C D'],['C','D E F','A B']]</p>

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

<p>Here is my code:</p>

<pre><code>x = []
myli = []

for item in Mylists:
    for i in range(len(item)):
        x.extend(item[i].split())
    myli.append(x)
</code></pre>

<p>You need to initialize x inside the outer forloop.</p>

<p>Your code</p>

<pre><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)
</code></pre>

<p>Correction</p>

<pre><code>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)
</code></pre>

python list