Python return list from function

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.


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

Simply do this:

network = splitNet()
print network

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)