1

I tried following with python lists

a = [1,2,3]
id(a)
3072380812L
a += [1]
print id(a)
3072380812L  # Same id, which means original list is modified
a = a + [1]
print id(a)
146238764    # Different id, which means new list is allocated and assigned to a

Why is this difference between "var += value" and "var = var + value" for python lists ?

Arovit
  • 3,579
  • 5
  • 20
  • 24

1 Answers1

3

+= modifies(if mutable) ... as you have seen, and = assigns also as you have seen ...

both operators are overridable in the classes and their behavior can also be changed at the whims of developers... you could make = do summing if you wanted to ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • I mean why is this difference ? isn't var += 1 treated as var = var + 1 in all languages ? – Arovit Dec 20 '13 at 16:29
  • no one modifies, the other assigns ... with ints it equates to the same since they are non mutable – Joran Beasley Dec 20 '13 at 16:32
  • 3
    "isn't var += 1 treated as var = var + 1 in all languages?" Python is a language, and it doesn't treat `+=` that way. So, obviously, no... – kindall Dec 20 '13 at 16:33