-3

Lets consider the following function:

def func():
    lizt = []
    for i in range(3):
        lizt.append(i)
    return lizt  

In Jupyter Notebook:
I type func() and i can see the correct output in the [out] cell: [0, 1, 2]

If i type lizt i receive the error message: name 'lizt' is not defined.
I know this is because the variable is locally defined within the variable. I don't think making it global would be the way to go, i simply think I need to understand better the concept... I mean aside from what is visible in the output, how to retrieve what has just been computed? Especially if i want to pass it to another function?

jim jarnac
  • 4,370
  • 7
  • 42
  • 78
  • 3
    Just assign the result to a new variable. `my_result = func()` – Andrew Guy Jan 06 '17 at 05:19
  • @Andrew Even though it's brief, it would be better to put in an answer rather than a comment, unless this question is a dupe... – David Conrad Jan 06 '17 at 05:21
  • @Andrew Guy Thank you. As simple as it is that's the answer. I know it's silly but sometimes when beginning the most simple things are difficult to resolve by just browsing google or other SO posts. – jim jarnac Jan 06 '17 at 05:22
  • @jim I think It's not possible to get the value of a variable outside the scope of a function in any programming language. You just call the function to pass the returned value of the function as Andrew shows in his example. – Vishal Nagda Jan 06 '17 at 05:24
  • 1
    [official Python tutorial](https://docs.python.org/3.6/tutorial/index.html) – TigerhawkT3 Jan 06 '17 at 05:28

1 Answers1

-1

assign to a new variable or in this way

def func():
    func.lizt = []
    for i in range(3):
        func.lizt.append(i)
    return func.lizt 

func()
print func.lizt

[0, 1, 2]
Will
  • 208
  • 1
  • 7