6

I've been toying a bit with python lists and I find the following a bit strange.

list = ["test"]
list + "test1" 
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

list += "test1"
print(list)
['test', 't', 'e', 's', 't', '1']

Can somebody help me understand why the += works but the + doesn't?

Also, I would have expected "test1" to be appended as a single element. Why one element per letters?

Francois
  • 852
  • 6
  • 17
  • `list += ["test1"]` will do the latter thing you wanted – JacobIRR Feb 14 '18 at 22:20
  • 1
    `+=` is basically `list.extend()` with re-assignment. It is *not a concatenation*. – Martijn Pieters Feb 14 '18 at 22:26
  • Concatenation with `+` only works if the right-hand side is a list too. `list.extend()` takes *any iterable*. A string is an iterable of separate characters, so you get each character of your input string added. – Martijn Pieters Feb 14 '18 at 22:27
  • If you want to append a single element in-place, use `list.append()`. – Martijn Pieters Feb 14 '18 at 22:28
  • @JoshuaTaylor: well, `list_a + list_b` produces a new list with the elements combined. `list_a.extend(list_b)` is the in-line equivalent of that operation, which is why `list_a += list_b` is essentially the same (but with additional re-assignment back to `list_a`). Because `list.extend()` accepts *any iterable* that also means that `+=` is a little more flexible than concatenation (but it is not hard to just use `list_a + list(object_b)`) – Martijn Pieters Feb 14 '18 at 22:30
  • @Mark_M: why the `str.split()`? Just to create a list with a single element? No, use `list_a + ['hello']` instead, explicitly put your string into a list with one element. – Martijn Pieters Feb 14 '18 at 22:31
  • To support what Martijn said, source code of [list concatenation](https://github.com/python/cpython/blob/master/Objects/listobject.c#L465) and [extend](https://github.com/python/cpython/blob/master/Objects/listobject.c#L816) – Reti43 Feb 14 '18 at 22:31
  • You're right @MartijnPieters - that's better. – Mark Feb 14 '18 at 22:32

0 Answers0