Skip to content Skip to sidebar Skip to footer

Remember Array Value After Function Call

If I write this: c = [] def cf(n): c = range (5) print c if any((i>3) for i in c) is True: print 'hello' cf(1) print c Then I get: [1, 2, 3, 4] hello []

Solution 1:

In python you can read global variables in functions, but you cant assigned to them by default. the reason is that whenever python finds c = it will create a local variable. Thus to assign to global one, you need explicitly specify that you are assigning to global variable.

So this will work, e.g.:

c = [1,2,3]

defcf(): 
    print(c) # it prints [1,2,3], it reads global c

However, this does not as you would expect:

c=[1,2,3]

def cf():c=1# c is local here.
    print(c)# it prints 1


cf()
print(c)# it prints [1,2,3], as its value not changed inside cf()

So to make c be same, you need:

c=[1,2,3]

def cf(): 
    global cc=1# c is global here. it overwrites [1,2,3]
    print(c)# prints 1


cf()
print(c)# prints 1. c value was changed inside cf()

Solution 2:

To summarise a few of these answers, you have 3 basic options:

  1. Declare the variable as global at the top of your function
  2. Return the local instance of the variable at the end of your function
  3. Pass the variable as an argument to your function

Solution 3:

You can also pass the array c into the function after declaring it. As the array is a function argument the c passed in will be modified as long as we don't use an = statement. This can be achieved like this:

defcf(n, c):
  c.extend(range(5))
  print c
  ifany((i>3) for i in c) isTrue:
    print'hello'if __name__ == '__main__':
  c = []
  cf(1, c)
  print c

For an explanation of this see this

This is preferable to introducing global variables into your code (which is generally considered bad practice). ref

Solution 4:

Try this

c = []

defcf(n):
  global c
  c = range (5)
  print c
  ifany((i>3) for i in c) isTrue:
    print'hello'

cf(1)

print c

Solution 5:

If you want your function to modify c then make it explicit, i.e. your function should return the new value of c. This way you avoid unwanted side effects:

defcf(n, b):
    """Given b loops n times ...

    Returns
    ------
    c: The modified value
    """
    c = [transformation of b]
    ...
    return c  # <<<<------- This

c = cf(1)

Post a Comment for "Remember Array Value After Function Call"