Python overview mutable and immutable

First, I'll start, like everyone else. I am new to python. My teacher gave me a problem:

def f(a, b, c):  
    a    = 1 
    c    = b 
    c[0] = 2 
a = 10 
b = [11, 12, 13] 
c = [13, 14, 15] 
f(a, b, c) 
print a, b, c

He prints:

10 [2, 12, 13] [13, 14, 15]

I understand that a stays at 10 because the integers are immutable, but I don't understand why b is changing and c is not working.

+5
source share
3 answers
c    = b 
c[0] = 2

Since you install con b, you can just as easily do this:

def f(a, b, unused): # notice c isn't in the parameter list  
    a = 1
    c = b # c is declared here
    c[0] = 2 # c points to b, so c[0] is b[0]

Now it’s obvious that it calways matches b, so why not just delete it:

def f(a, b, unused):
    a = 1
    b[0] = 2

And now it’s clear that you are changing the first element band are not doing anything with c, and remember that it is functionally identical to the original.

+4

:

def f(a, b, c):  
    a    = 1 # a is a single scalar value, so no pointing involved
    c    = b # point the local "c" pointer to point to "b"
    c[0] = 2 # change the 2nd value in the list pointed to by "c" to 2

f (a, b, c), b . "c" "c" .

+2

a 10, . 10, , a = 1 f(), .

c = b f(), c , b. , .

0

All Articles