0
def test(nums):
    nums = list(set(nums))

nums = [1,2,3,4,1,2,3,4]
test(nums)
print(nums)

[1,2,3,4,1,2,3,4]

I am not able to understand the process. If I do something like

def test(nums):
    nums.append(7)

nums = [1,2,3,4,1,2,3,4]
test(nums)
print(nums)

[1,2,3,4,1,2,3,4,7]

the list alters.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • It’s a case of *assignment* (into the local scope) vs *mutating* the original object. – S3DEV Nov 04 '22 at 19:09

1 Answers1

1

everything is object in python when you are using object method inside any function then python changes that object depending upon that method. append is inplace in your case

In this case,

def test(nums):
    nums.append(7)

nums = [1,2,3,4,1,2,3,4]
test(nums)
print(nums)

nums is list object, and you are calling append method on that list object which is inplace so it is changing the original list.

While in this case,

def test(nums):
    nums = list(set(nums))

nums = [1,2,3,4,1,2,3,4]
test(nums)
print(nums)

you have passed your list object to your function, but nums = list(set(nums)) in this line, you assigned a new list object to nums and previous nums is lost.

for clarification you can print the id of these objects,

def test(nums):
    print(id(nums)) # this will be original list id
    nums = list(set(nums))
    print(id(nums)) # this will be changed

nums = [1,2,3,4,1,2,3,4]
print(id(nums)) # this will be original list id
test(nums)
print(id(nums)) # this will be original list id
print(nums)

and for other case,

def test(nums):
    print(id(nums)) # this will be original list id
    nums.append(7)
    print(id(nums)) # this will be original list id

nums = [1,2,3,4,1,2,3,4]
print(id(nums)) # this will be original list id
test(nums)
print(id(nums)) # this will be original list id
print(nums)

If you do

def test(nums):
  print(id(nums)) # this will be original list id
  nums[:] = [1,2,3]
  print(id(nums)) # this will be original list id


nums = [1,2,3,4,1,2,3,4]
print(id(nums)) # this will be original list id
test(nums)
print(id(nums)) # this will be original list id
print(nums)

In this case, also when you do slicing then __getitem__ and __setitem__ dunder methods are used, which change the list object inplace.

Deepak Tripathi
  • 3,175
  • 1
  • 8
  • 21