3

In the code below, I understand that inside the change_my_var() function, my_var is a local variable and so assignment to my_var would not change the global my_var.

However, that is not the case for my_dict (of dict type) and my_list (of list type). They change after change_my_dict() and change_my_list() are run. What should be the explanation behind?

my_dict = {}
my_list = []
my_var = None

def main():
    print('my_dict')
    print('before : ', my_dict)
    change_my_dict()
    print('after : ', my_dict)

    print()
    print('my_list')
    print('before : ', my_list)
    change_my_list()
    print('after : ', my_list)

    print()
    print('my_var')
    print('before : ', my_var)
    change_my_var()
    print('after : ', my_var)

def change_my_dict():
    my_dict['a'] = 'b'

def change_my_list():
    my_list.append('c1')

def change_my_var():
    my_var = 10

if __name__ == '__main__':
    main()

Output:

my_dict
before :  {}
after :  {'a': 'b'}

my_list
before :  []
after :  ['c1']

my_var
before :  None
after :  None
Roy
  • 507
  • 10
  • 22
  • 2
    In `my_dict['a'] = 'b'` you're not assigning to a global, but mutating the dict bound to the global name *my_dict*. Same goes for the list. Trying to find a dupe target for this, since there pretty much has to be one. – Ilja Everilä Jul 05 '17 at 10:06
  • In that case, what datatype does this rule apply to? I could imagine set, list and dict would be applicable. Any other datatypes too? – Roy Jul 05 '17 at 10:15
  • Anything that you mutate in place. Assignment and mutating an object are different things in this context. `my_var = 10` binds a value to the name, be it global or local. `my_list.append('c1')` and such mutate the referenced object. You should read https://nedbatchelder.com/text/names.html. – Ilja Everilä Jul 05 '17 at 10:17
  • It's not a question of "data type", it's about the difference between mutating an object's state and rebinding a variable. Try rebiding `my_dict` or `my_list` in your functions instead of mutating them and you'll find out... – bruno desthuilliers Jul 05 '17 at 10:19

0 Answers0