-4

For instance,

def T(x):
for i in range(1,len(x)-1):
        x[i]+=x[i-1]+2

def f(x):
    x=x+2
    return x

x=[1,2,3,4,5]
;T(x)
;print(x)
[1, 5, 10, 16, 5]

the variable x changes in this case but,

x=3
;f(x)
;print(x)
x=3

x does not change in this case.

why is this happening?

idjaw
  • 25,487
  • 7
  • 64
  • 83
Pero
  • 1

1 Answers1

1

Generally speaking, mutable object is passed as reference while immutable ones are passed by values.

To get same result as (1):

x = 3
x = f(x)
print(x)

You can check this web for more info on this.

dcwhcdhw
  • 59
  • 1
  • 2