Python function is changing the value of passed parameter

前端 未结 2 393
感动是毒
感动是毒 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:18

    mylist outside the function and passedvariable are the same list object. So changing the list is reflected everywhere. The same holds true for copyofdata in the third example. It is no copy, but the same list object again. To make a copy, you have to explicitly copy the list, in your case you even have to copy each element of the list, as they are also list-objects. Now for the second example row = row[:-1]: Here you make a copy of the list, except the last element. So the former row is not changed, but a new list object is bound the the same name row.

提交回复
热议问题