Python function is changing the value of passed parameter

前端 未结 2 392
感动是毒
感动是毒 2021-01-26 05:50

Here\'s an example of where I started

mylist = [[\"1\", \"apple\"], [\"2\", \"banana\"], [\"3\", \"carrot\"]]

def testfun(passedvariable):
    for row in passed         


        
2条回答
  •  野的像风
    2021-01-26 06:19

    Python passes everything by sharing (references passed as value, see call by sharing), however the integrated numeric and string types are immutable, so if you change them the value of the reference is changed instead of the object itself. For mutable types like list, make a copy (e.g. list(passedvariable)). If you are modifying mutable objects within a list (which can only contain references!) you will need to perform a deep copy, to do so use

    import copy
    copy.deepcopy(passedvariable)
    

    See https://docs.python.org/2/library/copy.html (available since Python 2.6)

    Note that since references themselves are passed by value, you cannot change a reference passed as a parameter to point to something else outside of the function (i. e. passedvariable = passedvariable[1:] would not change the value seen outside the function). A common trick is to pass a list with one element and changing that element.

提交回复
热议问题