1

Let's say my list a is [1,2,3] which points to address 53367992

>>> a = [1,2,3]
>>> id(a)
53367992

Now, when I add [9] to this list, I understand the change of address, now l points to 53368552

>>> a = a + [9]
>>> a
[1, 2, 3, 9]
>>> id(a)
53368552

In this below case, I do not understand why a is pointing to same address even after adding [4] to a

>>> a = [1,2,3]
>>> id(a)
53361720
>>> a += [9]
>>> a
[1, 2, 3, 9]
>>> id(a)
53361720

Could you guys please explain me what is the difference between a = a +[9] and a += [9] (how come this acts as appending) operation in list?

0

1 Answer 1

3

a list is mutable. methods like .append() (or += / __iadd__ for that matter) change the list itself (in-place) and do not create a new instance.

+ (__add__) on the other hand will return a fresh instance.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the answer @hiro, didn't know += statement is different from + statement

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.