Hanamichi
Hanamichi

Reputation: 177

id() function in Python

In the following code:

L = [1,2,3]
addr1 = id(L)
L = L + [4,5]
addr2 = id(L)
L = [1,2,3]
addr3 = id(L)
L += [4,5]
addr4 = id(L)
print addr1 == addr2
print addr3 == addr4

The answer is False, True, but why?

I thought the L += [4,5] is just the short hand for L = L +[4,5].

Upvotes: 1

Views: 99

Answers (2)

Patrick Maupin
Patrick Maupin

Reputation: 8127

Objects can implement the __iadd__ special method, which means "in-place add".

Lists implement this.

You can do this with your own objects, and either choose to return the original object or a new one.

Upvotes: 3

Barmar
Barmar

Reputation: 780798

x += y is not exactly equivalent to x = x + y when x is a list. When it's a list, += performs an in-place modification to the list rather than creating a new list with the concatenation. But + always creates a new list.

Upvotes: 3

Related Questions