Why can a function modify some arguments as perceived by the caller, but not others?

前端 未结 11 1196
盖世英雄少女心
盖世英雄少女心 2020-11-21 07:10

I\'m trying to understand Python\'s approach to variable scope. In this example, why is f() able to alter the value of x, as perceived within

11条回答
  •  情歌与酒
    2020-11-21 07:51

    It´s because a list is a mutable object. You´re not setting x to the value of [0,1,2,3], you´re defining a label to the object [0,1,2,3].

    You should declare your function f() like this:

    def f(n, x=None):
        if x is None:
            x = []
        ...
    

提交回复
热议问题