Python Forum
local/global variables in functions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: local/global variables in functions (/thread-25694.html)



local/global variables in functions - abccba - Apr-08-2020

x = 1


def f1(y):
    y += 1
    return y


x1 = f1(x)
print('x = ', x, '  x1 = ', x1)
answer:
x = 1 x1 = 2

x_list = ['1','2']


def f2(y_list):
    y_list[0] = '0'
    return y_list


x1_list = f2(x_list)
print('x_list = ', x_list, '  x1_list = ', x1_list)
answer:
x_list = ['0', '2'] x1_list = ['0', '2']

why in the first case the global variable is preserved and not in the second case?


RE: local/global variables in functions - stullis - Apr-08-2020

This isn't a matter of global versus local. Rather, it's a matter of Python's sequence implementation. Sequences, such as a list, store values by reference to a memory location. As a result, a list is basically a pointer used in other languages. This enables changes to a list made within a function to change the list outside the function.


RE: local/global variables in functions - abccba - Apr-08-2020

(Apr-08-2020, 01:59 PM)stullis Wrote: This isn't a matter of global versus local. Rather, it's a matter of Python's sequence implementation. Sequences, such as a list, store values by reference to a memory location. As a result, a list is basically a pointer used in other languages. This enables changes to a list made within a function to change the list outside the function.

variables also use a pointer to a certian memory location. why should there be a different approach in both cases?
though more than discussing the philosofy around it, I would prefer to know the way around and understand if there is a 'clean' way to preserve the content of lists, when passing them to a function.


RE: local/global variables in functions - ndc85430 - Apr-08-2020

Lists are mutable, integers are not. If you want an immutable sequence, use a tuple.


RE: local/global variables in functions - abccba - Apr-08-2020

it is a nice suggestion but does not solve the problem I was addressing.
The list is created while the program is running.
Is there away to creat a new list that uses another position in memory?

ok, it can be converted. Fine!


RE: local/global variables in functions - bowlofred - Apr-08-2020

You can make a copy of the list in your function
def f2(y_list):
    new_list = list(y_list)
    new_list[0] = '0'
    return new_list



RE: local/global variables in functions - jefsummers - Apr-08-2020

A nice video about this from PyCon: https://www.youtube.com/watch?v=_AEJHKGk9ns