0

I am new to python and trying to understand how lists and functions work. When I invoke the first function, it does not change the value of the variable b. Shouldn't this function change the value of the variable b rather than just returning the modified value when using print statement. On the other hand, after the second function is invoked, the value of the variable b is completely changed. What is the difference between these to function's effect on the variable?

b = [1,2,3,4]
def func(a):
    a = a[2:3]
    return a

print(func(b))
print(b) #Although the func is invoked the value of the variable is unchanged

def newFunc(t):
    t.append(5)

newFunc(b)
print(b)
quamrana
  • 37,849
  • 12
  • 53
  • 71
Tuna Ovul
  • 1
  • 2
  • Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Aug 22 '22 at 15:23
  • 1
    `func` is simply returning a slice of the argument, which is inferred to be a list object. `newFunc` appends data to the argument, which again is inferred to be a list object. Appending data to a list changes it's contents, while returning a slice does not. – h0r53 Aug 22 '22 at 15:25
  • This question touches on the idea of **mutability**, which in layman's terms is the ability of an object to be changed. Lists in Python are mutable objects, so when you pass a list as a function argument any changes to the list within the function are reflected to the object outside of the function. – h0r53 Aug 22 '22 at 15:26
  • @h0r53, I wouldn't have expected `newFunc` to change `b` without the use of the `global` keyword. Why isn't it needed here? – PangolinPaws Aug 22 '22 at 15:26
  • The function creates a new ´a´. It does not change the existing ´a´ (which is ´b´). This is how Python works. The assignment always creates a new thing without touching the original thing. This is all what can be said here. – habrewning Aug 22 '22 at 15:27
  • 1
    @PangolinPaws no `global` needed. `b` is passed as an argument to `newFunc`. Lists are mutable in Python, so changes to the list within the function are reflected to the object outside of the function. – h0r53 Aug 22 '22 at 15:28
  • @habrewning that is incorrect. Run the code and see for yourself that the globally scoped variable `b` has it's contents changed after calling `newFunc`. Changes to `a` within the function are reflected to the object outside of the function due to the mutability of the argument's type. – h0r53 Aug 22 '22 at 15:29

0 Answers0