0
def add_list(p):
    p = p + [1]

p1 = [1, 2, 3]
add_list(p1)
print p1


res:[1, 2, 3]

BUT

def add_list(p):
    p += [1]

p1 = [1, 2, 3]
add_list(p1)
print p1

res:[1, 2, 3, 1]

I don't know why, can someone explain this? What's the main difference between them?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
kker neo
  • 133
  • 4
  • 1
    Linked as a duplicate of [this](https://stackoverflow.com/questions/9766387/different-behaviour-for-list-iadd-and-list-add) which discusses exactly this behaviour. :) – wonderb0lt Jun 16 '15 at 10:57
  • 1
    See also http://stackoverflow.com/q/2347265/3001761. Augmented assignment gets even more interesting [with tuples](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works)! – jonrsharpe Jun 16 '15 at 10:57

0 Answers0