2

I ran the following code in Jupyter Notebook:

list_1 = []
list_1 += "cat"
print(list_1)

and got the following output:

['c', 'a', 't']

but when i ran this:

list_1 = []
list_1 = list_1 + "cat"
print(list_1)

it gave the following error:

TypeError: can only concatenate list (not "str") to list

I failed to understand this as in both the methods, a string is being added to a list.

Is it something about the '+=' notation or something related to the concatenation of lists and strings that's causing the bug?

  • There is an [excellent answer on the difference between + and +=](https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists). Beside that, note that Python tries to interpret β€œcat” as a list, which defaults to a list of the individual characters. – agtoever Jul 29 '18 at 08:04
  • I did check that answer. The problem I was interested in was the concatenation of a string to a list but that answer only addresses how the `+=` notation affects the concatenation of two lists. As you cleared it out that Python treats "cat" as a list of characters, I am able to completely understand the problem. Thanks – Hassaan Ahmad Jul 29 '18 at 21:48

1 Answers1

1

list_1 += "cat" is calling list_1.__iadd__ which uses list_1.extend("cat") internally and appends every character from the iterable "cat" to the list one by one.

list_1 + "cat" attempts to call list_1.__add__ and this method fails as you noticed because it expects two lists.

timgeb
  • 76,762
  • 20
  • 123
  • 145