Python return list from function

PythonListFunction

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Simply do this:

network = splitNet()
print network

Solution 2 - Python

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.

Solution 3 - Python

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:

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)

Solution 4 - Python

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']
>>>

Solution 5 - Python

Have you actually called the function yet? This works fine (in the Python interpreter)

 >>> def f():
 ...   network = []
 ...   network.append(1)
 ...   network.append(2)
 ...   network.append(3)
 ...   return network
 ...
 >>> network = f()
 >>> print network
 [1, 2, 3]

Solution 6 - Python

You may declare the name of the variable assigned to the list as global, like this:

def get_list():
    global destination_list
    destination_list = []
    destination_list.extend(('1','2','3'))
    return destination_list

get_list()
print(destination_list)

Solution 7 - Python

L=[1, 2, 3]

def rl(l): 
    return l

[*ll] = rl(L) # ll is in a list

ll
# >>> [1, 2, 3]

*t, = rl(L)   # ll is in a tuple

t
# >>> [1, 2, 3]

Solution 8 - Python

If you want to return an item or list from a definition, you could define it before hand and use it as a variable during the initial writing of said definition. Unless it has to be defined within the definition. In this case you won't need to write in a return command at the end.

network = []

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)

print network # Will print the list you've appended. But it is now a usable object. 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThomas MitchellView Question on Stackoverflow
Solution 1 - PythonAlex CoplanView Answer on Stackoverflow
Solution 2 - PythonsberryView Answer on Stackoverflow
Solution 3 - PythonphihagView Answer on Stackoverflow
Solution 4 - PythonRanRagView Answer on Stackoverflow
Solution 5 - PythonChris TaylorView Answer on Stackoverflow
Solution 6 - PythonVictorView Answer on Stackoverflow
Solution 7 - PythonRathinavelu MuthaliarView Answer on Stackoverflow
Solution 8 - PythonLord PantaloonView Answer on Stackoverflow