0

I'm new to python, there are many concepts I still trying to understand. Can anyone explain me why this is the case?

def func(x):
    x = 3
    return

x = 1
print x
func(x)
print x

OUTPUT:
1
1

But, if x is a list:

def func(x):
    x[0] = 3
    return

x = [1]
print x
func(x)
print x

OUTPUT:
[1]
[3]

Why?

Pedro Batista
  • 1,100
  • 1
  • 13
  • 25
  • 3
    See https://nedbatchelder.com/text/names.html. – user2357112 Feb 28 '17 at 18:00
  • One is mutable and one is not. – scrappedcola Feb 28 '17 at 18:02
  • The first example is trying to change the actual parameter, the second example changes an object the parameter points to – Jerfov2 Feb 28 '17 at 18:03
  • You *can* actually change variables from inside a function. Look up the documentation for the [**global** statement](https://docs.python.org/3.6/reference/simple_stmts.html#the-global-statement). – Roland Smith Feb 28 '17 at 18:06
  • 1
    Check [this question](http://stackoverflow.com/a/534383/4796694). As @scrappedcola mentioned, it is because lists are mutable and numbers are not. So when you modify a number, python is actually creating a new number variable, leaving the outer number unchanged. – JavoSN Feb 28 '17 at 18:23
  • It can be difficult for programmers coming from other languages to fully grasp the way that Python does this stuff. The linked question is good, especially the answer by David Cournapeau, and you should definitely study that article by Ned Batchelder. IMHO, it's best to try and understand the Python data model on its own terms, don't try to understand it in terms of other languages' data models. So forget about pointers, call by reference, etc, and embrace the concept of objects being bound to names. – PM 2Ring Mar 01 '17 at 03:22

0 Answers0