Python function is changing the value of passed parameter -
here's example of started
mylist = [["1", "apple"], ["2", "banana"], ["3", "carrot"]] def testfun(passedvariable): row in passedvariable: row.append("something else") return "other answer" otheranswer = testfun(mylist) print mylist
i'd expected mylist
not have changed.
i tried remove temporary column, didn't work:
mylist = [["1", "apple"], ["2", "banana"], ["3", "carrot"]] def testfun(passedvariable): row in passedvariable: row.append("something else") # i'm finished "something else" column, remove row in passedvariable: row = row[:-1] return "other answer" otheranswer = testfun(mylist) print mylist
i think tried use different reference:
mylist = [["1", "apple"], ["2", "banana"], ["3", "carrot"]] def testfun(passedvariable): copyofdata = passedvariable row in copyofdata: row.append("something else") # i'm finished "something else" column, remove row in copyofdata: row = row[:-1] return "other answer" otheranswer = testfun(mylist) print mylist
i've written little python scripts few months now, never come across before. need learn about, , how pass list function , temporarily manipulate (but leave original untouched?).
python passes sharing (references passed value, see call sharing), integrated numeric , string types immutable, if change them value of reference changed instead of object itself. mutable types list, make copy (e.g. list(passedvariable)
). if modifying mutable objects within list (which can contain references!) need perform deep copy, use
import copy copy.deepcopy(passedvariable)
see https://docs.python.org/2/library/copy.html (available since python 2.6)
note since references passed value, cannot change reference passed parameter point else outside of function (i. e. passedvariable = passedvariable[1:] not change value seen outside function). common trick pass list 1 element , changing element.
Comments
Post a Comment