Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python return list from function

I have a function that parses a file into a list. I'm trying to return that list so I can use it in other functions.

def splitNet():     network = []     for line in open("/home/tom/Dropbox/CN/Python/CW2/network.txt","r").readlines():         line = line.replace("\r\n", "")         line = string.split(line, ',')         line = map(int, line)         network.append(line)     return network 

When I try to print the list outside of the function (for debugging) I get this error:

NameError: name 'network' is not defined 

Is there something simple I am doing wrong or is there a better way to pass variables between functions without using globals?

like image 250
Thomas Mitchell Avatar asked Feb 16 '12 18:02

Thomas Mitchell


People also ask

Can we return list from function?

A Python function can return any object such as a list. To return a list, first create the list object within the function body, assign it to a variable your_list , and return it to the caller of the function using the keyword operation “ return your_list “.

How do you access a list outside a function in Python?

You simply pass a call to function generating your list as an argument (instead of global variable) to a call to function processing the list you want to generate.

Can I return multiple values from a function in Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.


1 Answers

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

Simply do this:

network = splitNet() print network 
like image 127
Alex Coplan Avatar answered Sep 18 '22 16:09

Alex Coplan