Python return list from function

Variables cannot be accessed outside the scope of a function they were defined in.

Simply do this:

network = splitNet()
print network

I assume you are not assigning the returned value to a variable in scope.

ie. you can't do

splitNet()
print network

instead you would

network = splitNet()
print network

or for that matter

my_returned_network_in_scope = splitNet()
print my_returned_network_in_scope

otherwise you could declare network outside of the splitNet function, and make it global, but that is not the recommended approach.


The names of variables in a function are not visible outside, so you need to call your function like this:

networks = splitNet()
print(networks)

A couple of other notes:

  • You may want to convert your function to an iterator, using yield.
  • You don't need to call readlines; the function itself is an iterator.
  • Your function may be leaking the file handle. Use the with statement.
  • You can use str.split, which is more readable and easier to understand than string.split.
  • Your file looks to be a CSV file. Use the csv module.

In summary, this is how your code should look like:

import csv
def splitNet():
    with open("/home/tom/Dropbox/CN/Python/CW2/network.txt") as nf:
        for line in csv.reader(nf, delimiter=','):
            yield map(int, line)
network = list(splitNet())
print (network)

Your function is returning a list so you have to assign it to a variable and than try to print it.

network = splitNet()
print network

For example

>>> def mylist():
...    myl = []
...    myl.append('1')
...    return myl
...
>>> my_list = mylist()
>>> my_list
['1']
>>>