0

I was tinkering with lists and stumbled upon something suprising. Here is the code:

l1=[1,2,3,4]   #Statement-1
l1[1:3]+="Tea" #Statement-2 (the one that I didn't understand)
print(l1)      #>>>[1, 2, 3, 'T', 'e', 'a', 4]

So what I inferred from the above code is that there is a homogeneous list named l1. And we know that we can only concatenate iterables of the same type. So I assumed what Statement-2 does is: l1[1:3]=l1[1:3]+"Tea" as we know x += 1 > x = x + 1 as a general rule. But how can we add lists with strings?

Moreover, when I typed a similar code with the aim of understanding it better, I got an error. Here's the code:

l1=[1,2,3,4]
l1[1:3]=l1[1:3]+"Tea"
print(l1)
TypeError: can only concatenate list (not "str") to list

Could someone explain what's going on with statement 2 in detail?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
magnetar
  • 11
  • 1
  • For lists `+=` is basically `.extend`, which can take any iterable. `x += 1` isn't always `x = x + 1`, it depends on [`__iadd__`](https://docs.python.org/3/reference/datamodel.html#object.__iadd__). – jonrsharpe Dec 20 '21 at 10:16

0 Answers0