digolira2
digolira2

Reputation: 411

".append" and "+" semantic difference inside of functions

I'm having some trouble to understand what is the difference between these 3 examples.

#example1    
list1 = [1,2,3,4]
list1= list1+[6]
list1.append(1000)
print("Example 1: ", list1)

# example 2
def f(j):
  j= j + [6]
  j.append(1000)

list2 = [1,2,3,4]
f(list2)
print("Example 2: ", list2)

# example 3
def f(j):
  j.append(1000)
  j= j +[6]

list3 = [1,2,3,4]
f(list3)
print("Example 2: ", list3)

Output:

Python Output

The first one I did some simple addition using (+) and (.append), it worked fine.

The second one I created a function. I guess I understood the results. In my opinion, it remained the same because the changes that I've done in the original list were only made locally, so, after the function had finished, the original list have remained the same. Am I right?

The third one I can't understand. Because it is exactly like the second one, I've just changed the order of the elements, however the output is completely different.

Upvotes: 1

Views: 108

Answers (1)

chepner
chepner

Reputation: 530990

Example 2 creates a new list with j = j + [6], and the only reference to the that list is the local variable j, so the change is not visible after f returns.

Example 3 appends the value to the original list referenced by j, which list3 still refers to.

Upvotes: 6

Related Questions