2

If I have a function in Python like this that calculates the sum of the elements in a list:

def sum_it(_arr):
    if len(_arr) <= 1:
        raise ValueError("The input must be a list of length > 1")
    _init = 0
    for i in range(len(_arr)):
        _init += _arr[i]
    _sum = _init
    return _sum

No I call the function like this and I execute it.

result = sum_it([1, 2, 3, 4])

My problem is: if I do not save the result into a text file or I do not print result, where can I access it? Do I have to re-execute the code in order to access to the output?

I mean, in MATALB for example, when I have something like this and I run it, I will have a workspace where all my variables and outputs are stored. Is it possible to do this in Python?

I hope I am not asking wrong question.

Chiba
  • 91
  • 4
  • how did you execute your code? – farhawa Jun 09 '15 at 14:41
  • I am using Pycharm. So I just run it from the editor. – Chiba Jun 09 '15 at 14:42
  • 4
    Please stop using initial underscores. It's a style reserved for private members of classes, or indicates unused variables. Neither is the case for you. Additionally, you are doing list iteration wrong. Most of the time, you do *not* want to access a sequence by index, but instead directly iterate. So `for item in _arr: _init += item` instead of your much more complex expression. Last but not least, there is the builtin `sum` that already does what you want, in case you didn't know. – deets Jun 09 '15 at 14:42
  • 1
    why do you need to reimplement the builtin [`sum()`](https://docs.python.org/2/library/functions.html#sum)? – mata Jun 09 '15 at 14:43
  • 2
    try `ipython` it works like matlab command with `execfile(PATH)` when you want to execute some script – farhawa Jun 09 '15 at 14:43
  • @mata it is just an example to illustrate my problem. – Chiba Jun 09 '15 at 14:48
  • Just my 2 cents, MATLAB is a rather unique product and I would not expect to find 100% analogous solutions in Python. Same goes for other programming languages. In fact, most of solutions you'll find probably was design to mimic MATLAB behavior. – Łukasz Rogalski Jun 09 '15 at 14:48

1 Answers1

3

They are kept in memory so, as long as the process doesn't die, you'd be able to access 'result' until you re-assign it or your code get out of result's scope (see more about scope in [1])

To access 'result' value once python process has died, only way is if you have saved it to a file, printed to console or sent it through netowrk to another device which keeps its value, as memory used by processes is freed for use by another one (see more about processes life cycle in [2]).

[1] Short Description of the Scoping Rules?

[2] http://www.linux-tutorial.info/modules.php?name=MContent&pageid=84

Community
  • 1
  • 1
XiR_
  • 222
  • 1
  • 8