-1

Consider the following code:

def test(Tlist):
    Tlist.sort(reverse=True)

Tlist=[0.02,0.1,4,35]
print(Tlist)# [0.02, 0.1, 4, 35]
test(Tlist)
print(Tlist)# [35, 4, 0.1, 0.02]

def test2(a):
    a+=1

a=0
print(a)# 0
test2(a)
print(a)# 0

What confuses me is that in the first function test, the list Tlist is being modified. But in the function test2, the variable a is not.

But conceptually both are sent as parameters to my functions. I don't understand why the list is being modified ? I thought that sending a variable to a parameter of a function would have for effect that this variable is not changed globally within the function.

StarBucK
  • 209
  • 4
  • 18
  • 1
    `Tlist.sort` *mutates* the `Tlist` object, of which there's only one, so changes are seen by anyone holding a reference to that object. `a+=` assigns a new value to the local variable `a`, which is only visible inside the function. – deceze Feb 15 '21 at 11:40
  • 1
    @Anonymous "pass by value" or "pass by reference" don't apply here. With `a += 1` you rebind the name `a` to a new value. The original value `a` was bound to doesn't change. – Matthias Feb 15 '21 at 11:43

1 Answers1

0

The sort function modifies the input list itself.

>>> a = [1,2,3,5,1000,12]
>>> a.sort()
>>> a # original list changes
[1, 2, 3, 5, 12, 1000]

>>> a = [1,2,3,4,100,1000, 12]
>>> x = sorted(a)
>>> a #original list no change
[1, 2, 3, 4, 100, 1000, 12]
>>> x  
[1, 2, 3, 4, 12, 100, 1000]
Simplecode
  • 559
  • 7
  • 19