-1

Can please someone explain why the the following operations have not equal outcome when passed to a function?

lis=lis+[1]
lis+=[1]

Shouldn't that be the same?

The problem derives from the following code:

def f1(lis):
    lis=lis+[1]
    print(id(lis))

list1=[0]
print("before function", id(list1))
f1(list1)
print("after function", id(list1))
print(list1)

before function 45004000
45004160
after function 45004000
[0]

Why is "1" not added to list1 like it does below?

def f1(lis):
    lis+=[1]
    print(id(lis))

list1=[0]
print("before function", id(list1))
f1(list1)
print("after function", id(list1))
print(list1)

before function 45200888
45200888
after function 45200888
[0, 1]

TrebledJ
  • 8,713
  • 7
  • 26
  • 48
KideW
  • 45
  • 4

1 Answers1

0

As you could see from the output for your first snippet, the id(lis) changes after you assign lis + [1]. What lis + [1] does is create a new list, which you then assign back to lis. That's why you get different ids (45004000 versus 45004160 in your case). This will not persist as a reference to list1.

On the other hand, lis += [1] mutates lis, changing it in-place. You can tell it does this in place because of the consistent id (45200888 in your output). Being under the same id as before, this will persist back to list1, mutating it as well.

TrebledJ
  • 8,713
  • 7
  • 26
  • 48