0
l = list()

l = l + "string" #throws error
l += "string" #works

I was just wondering why this strange behaviour since we were taught l = l + "something" is the same as l += "something".

Henry
  • 39
  • 4
  • 1
    Well, the only sensible conclusion is: these are not the same, and someone taught you incorrectly. And in fact it is an inconsitency that `+` works with lists only while `+=` with any iterable. There's not really much more to say about it. – freakish Jan 12 '22 at 13:44
  • 1
    Look at the contents of `l` and you might get a better idea... – MattDMo Jan 12 '22 at 13:45
  • `l += x` is only equivalent to `l = l + x` if `l.__iadd__` is undefined or defined to be equivalent to `l.__add__`. – chepner Jan 12 '22 at 13:46
  • 1
    Your title is inaccurate. You can't append a string with `+=`; it's not the whole string that gets added to the list, but each character in the string individually. – chepner Jan 12 '22 at 13:47
  • "we were taught `l = l + "something"` is the same as `l += "something"`" you were taught incorrectly. – juanpa.arrivillaga Jan 12 '22 at 13:53

1 Answers1

4

+ requires a list when adding to a list.

+= only requires an iterable when updating a list. A str value is (for better or worse) an iterable of single-character strings, so that

l += "string"

causes 's', 't', 'r', etc to be appended to l. The += operator is more or less equivalent to

l.extend("string")
chepner
  • 497,756
  • 71
  • 530
  • 681
  • It's not "more or less equivalent", it's the same. – deceze Jan 12 '22 at 13:48
  • `l.extend(...)` is an expression statement which also produces the value `None`. `l += ...` is an assignment statement with no value of its own. – chepner Jan 12 '22 at 13:50
  • I *could* (though I can't imagine why I'd want to) write `print(l.extend(...))`, but `print(l += ...)` is a syntax error. – chepner Jan 12 '22 at 13:50
  • Oookay, except for those nitpicky details, they're [the same operation](https://docs.python.org/3.10/library/stdtypes.html#typesseq-mutable) as far as the list is concerned. ;) – deceze Jan 12 '22 at 13:51