create a list but getting a string?
<pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&amp;:L,M,N
"""

def read_nodes(gfile):
    for line in gfile.split():
        nodes = line.split(":")[1].replace(';',',').split(',')
        for node in nodes:
            print node

print read_nodes(s)
</code></pre>

<p>I am expected to get <code>['A','B','C','D','E',.....'N']</code>, but I get <code>A B C D E .....N</code> and it's not a list. I spent a lot of time debugging, but could not find the right way.</p>

<p>I believe this is what you're looking for:</p>

<pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&amp;:L,M,N
"""

def read_nodes(gfile):
    nodes = [line.split(":")[1].replace(';',',').split(',') for line in gfile.split()]
    nodes = [n for l in nodes for n in l]
    return nodes

print read_nodes(s) # prints: ['A','B','C','D','E',.....'N']
</code></pre>

<p>What you were doing wrong is that for each sub-list you create, your were iterating over that sub-list and printing out the contents. </p>

<p>The code above uses list comprehension to first iterate over the <code>gfile</code> and create a list of lists. The list is then flattened with the second line. Afterwards, the flatten list is returned.</p>

<p>If you still want to do it your way, Then you need a local variable to store the contents of each sub-list in, and then return that variable:</p>

<pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&amp;:L,M,N
"""

def read_nodes(gfile):
    all_nodes = []
    for line in gfile.split():
        nodes = line.split(":")[1].replace(';',',').split(',')
        all_nodes.extend(nodes)
    return all_nodes

print read_nodes(s)
</code></pre>

python list debugging