Python: Modify Global list inside a function

后端 未结 5 1751
耶瑟儿~
耶瑟儿~ 2020-11-30 09:21

First of all, I understand that I can use global statement to access global variables. But somehow I was able to modify a global list without global

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 10:01

    It is of concept based on mutable and immutable objects in Python. In your case, for example:

    a=[1,2]
    def myfn():
        a=[3,4]
        print id(a)
    
    >>>id(a)
    3065250924L
    >>>myfn()
    3055359596
    

    It is clear both are different objects. Now:

    a=[1,2]
    def myfn():
        a[:] =[3,4]
        print id(a)
    
    >>>id(a)
    3055358572
    >>>myfn()
    3055358572
    

    That means it is same variable using in local and global scope.

提交回复
热议问题