-2

My mind is confused. Why argument(L) changed here, shouldn't it be preserved?

L = [5,2,1,1,2,4,3,5]
def get_unique_list(list):
    for values in list:
        index=list.index(values)
        for values2 in list[index+1:]:
            if values==values2:
                del list[list.index(values2)]
    
get_unique_list(L)
print(L)

output is


[1, 2, 3, 4, 5]

  • It is a list so it is passed by reference. no copies of lists are made unless you explicitly make a copy of the list – Erik McKelvey Dec 07 '21 at 22:10
  • 2
    In addition, naming a variable `list` can be dangerous and should not be considered good practice. This is in conflict with the `list` keyword. – Kaz Dec 07 '21 at 22:19
  • 1
    Not a good idea to name the parameter (or a variable) `list` because that overrides the builtin `list`. But this is one of those traps in Python for the unwary/learner, like mutable parameters, despite the ‘least surprise’ claim/aim. – DisappointedByUnaccountableMod Dec 07 '21 at 22:20
  • @Kaz - `list` is a *type*, rather than a keyword. – S3DEV Dec 07 '21 at 22:23
  • Also this: https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it – Woodford Dec 07 '21 at 22:25

1 Answers1

0

Python effectively passes mutable objects by reference: When you write 'get_unique_list(L)', this passes a reference ("L") to an object (the list itself, stored in memory) into the function, where it is assigned a new local reference name 'list'. Because lists are mutable data, no new copy of the object is made, and so changes that occur inside the function affecting 'list' change the object that L still references outside of it.

A more complete answer is here: How do I pass a variable by reference?

Halbert
  • 142
  • 7
  • 1
    It passes *a reference to* the object; or more plainly, it’s location in memory. It does *not* pass the object itself. – S3DEV Dec 07 '21 at 22:21
  • 1
    You don’t need ‘effectively’. Python passes mutable object by reference. – DisappointedByUnaccountableMod Dec 07 '21 at 22:21
  • @S3DEV -- indeed, though I think this language is all a bit slippery; I've seen others claim that all python references are by value, but the value is the address of the reference. Making a change though. – Halbert Dec 08 '21 at 05:23