Why does my function overwrite a list passed as a parameter?

前端 未结 4 667
温柔的废话
温柔的废话 2020-12-20 18:14

I have created a function that takes a list as a parameter. It shuffles the list, replaces the first element and returns the new list.

import random
firstLi         


        
4条回答
  •  青春惊慌失措
    2020-12-20 18:53

    It does not replace the first list. The first list is passed by reference meaning that any mutations you perform on the list that is passed as the parameter, will also be performed on the list outside of the function, because it is the same list.

    However, Strings and other basic types are not passed by reference and therefore any changes you make in your function scope is tot he local copy of the variable only.

提交回复
热议问题