2

I found something puzzled me in Python earlier on, let's say I got a list of chars l = ['a','b']

when I do l + 'c' it gives me error of 'can only concatenate list (not "str") to list'. However l += 'c' is fine which gives me l = ['a', 'b', 'c']. Does anyone know why that is? (I am on Python 3.7.0)

  • 1
    good read ... https://stackoverflow.com/questions/4841436/what-exactly-does-do-in-python – iamklaus Oct 11 '18 at 15:07
  • 1
    I disagree with the dup. This question is specifically about `+` vs `+=` on the list type. A question about the general behavior of the `+` and `+=` desugaring is not the same thing. – Silvio Mayolo Oct 11 '18 at 15:11
  • 1
    Does the duplicate really answer why _in this special case_ `list + str` does not work, but `list += str` is interpreted as `list += list(str)`? – tobias_k Oct 11 '18 at 15:11
  • `+=` means "extend this list with the given items" (the items in this case being the sequence of characters in the string). `+` means "concatenate these two lists into a new list". – khelwood Oct 11 '18 at 15:15

1 Answers1

2

With l + 'c', you are trying to merge a string and a list. But with l += 'c', you’re essentially doing the same as l.extend('c').

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
DanDeg
  • 316
  • 1
  • 2
  • 7
  • 3
    That's not entirely correct. `l += 'c'` will `extend`, not `append` to the list. – tobias_k Oct 11 '18 at 15:08
  • ...which is why `l += 'cd'` will give you `l = ['a', 'b', 'c', 'd']`. – Tim Pietzcker Oct 11 '18 at 15:09
  • To be perfectly clear, `+=` works for *any* iterable, and strings are iterable. It's not a special case for strings; it's just that the natural behavior of `+=` (and `extend`, as already pointed out) works here, whereas `+` is specialized for lists. Good answer though! – Silvio Mayolo Oct 11 '18 at 15:10
  • Sorry, I didn’t know about the extend part – DanDeg Oct 11 '18 at 15:11