Assigning global and local variables of different types in Python

In the code below, I understand that inside the function change_my_var()

my_var

is a local variable, so the assignment my_var

will not change the global my_var

.

However, this is not the case for my_dict

(dict type) and my_list

(list type). They change after change_my_dict()

and change_my_list()

. What should be the explanation?

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

      

+3


source to share





All Articles