Loading...
I passed a list to a function and appended an item inside it. To my surprise the original list outside also changed. Lists confuse me, why does this happen?
Lists in Python are mutable and are passed by reference, meaning the function receives a link to the same list object, not a fresh copy. So when you do 'mylist.append(10)' inside the function, you are modifying the one and only list, and the change is visible everywhere. This does not happen with numbers or strings because they are immutable. If you want the function to leave the original untouched, pass a copy: send 'mylist[:]' or 'mylist.copy()', or make the copy inside the function before changing it. So remember: methods like append, remove and sort change the list in place and affect the original, while building a new list keeps the original safe.
Sign in as a tutor to answer this doubt.