Python: Modify Global list inside a function

后端 未结 5 1762
耶瑟儿~
耶瑟儿~ 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:14

    There are two reasons for this result:

    1. Variables are simply names that refer to objects
    2. List is mutable

    In func1,nums refer to a new object because a new list is created. Therefore global nums is not affected.

    In func2, the modification is applied to the object passed in. Thus global nums is changed. A new object is not created because list is mutable.

    ref: https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

提交回复
热议问题