Assignment to global vs local variables of different types in Python

Viewed 25

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
0 Answers
Related