0

I decided to get know the Python data model and mutability concept, and after that "gotta" moment one test crashed my happiness.

I am completely ok with this example:

x = ['1']
def func(a):
    b = 'new value'
    a.append(b)   

func(x)
print(x) # expected  ['1', 'new value']

BUT ! What is hapenning here ?

x = ['1']
def func(a):
    b = 'new value'
    a = b
    print(a)
    # expected  'new value'
    # factual  'new value'


func(x)
print(x)
# expected  'new value'
# factual ['1'] !!!

Why x does not equal to 'new value' ?

Edgar Navasardyan
  • 3,731
  • 7
  • 49
  • 103

1 Answers1

1

In the first example, both x and a are pointing to the same list. So when you append a value to that list using the a reference, you see that side effect after the function returns.

In the second example, you reassign the local variable a to point to a new value, but x still points to the original list. After the function returns, a goes away, but x still points to the list.

Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861