Home > OS >  need to save a global variables coming from the same function() in python()
need to save a global variables coming from the same function() in python()

Time:05-21

I made a toy function where I would need to save certain values that are given to this function... to perform this I usually declare this storing variable x as global..

But if I need to call this function several times inside the same code, the same global var xobviously will be the result of each time the function is called.

How can I obtain this simple task?

this below is the toy example.

import numpy as np
import pandas as pd

def _foo_append_(x_i,count):               
    global x

    if count==0:
        x = []

    x.append(x_i)

    return x


for i in range(0,10):
    rv_1 = np.round(np.random.normal(10,5),decimals=2)
    rv_2 = np.round(np.random.normal(22,3),decimals=2)

    keep_1 = _foo_append_(x_i=rv_1,count=i)
    keep_2 = _foo_append_(x_i=rv_2,count=i)

the output should be two arrays keep1 and keep2 of 10 elements both, but I'm getting both arrays of 20 elements..

How to achieve this? Thank you

CodePudding user response:

Using global/nonlocal variables makes it difficult to keep the different lists straight, since they both share the same name in the same scope. You should instead initialize each array separately.

Your example could be written much more simply (and correctly) as:

import numpy as np


keep_1 = [np.round(np.random.normal(10,5),decimals=2) for _ in range(10)]
keep_2 = [np.round(np.random.normal(22,3),decimals=2) for _ in range(10)]

If your "real" example is more complex and you can't use a list comprehension, or you can't actually declare the different keeps as different named variables, here's an example that uses your _foo_append_ (minus the unnecessary global var stuff it's just a simple call to append) and a list of lists that keeps track of the keep_n lists:

def _foo_append_(x, x_i):
    x.append(x_i)


params = [(10, 5), (22, 3)]
keeps = []
for p in params:
    keeps.append([])
    for _ in range(0, 10):
        _foo_append_(keeps[-1], np.round(np.random.normal(*p), decimals=2))
  • Related