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

前端 未结 11 1221
盖世英雄少女心
盖世英雄少女心 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:49

    n is an int (immutable), and a copy is passed to the function, so in the function you are changing the copy.

    X is a list (mutable), and a copy of the pointer is passed o the function so x.append(4) changes the contents of the list. However, you you said x = [0,1,2,3,4] in your function, you would not change the contents of x in main().

提交回复
热议问题