Inconsistency of Python plus operator
In [26]: l=[]
In [27]: s="asdsad"
In [28]: l+=s
In [29]: l
Out[29]: ['a', 's', 'd', 's', 'a', 'd']
However,
In [30]: l+s
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/xiaohan/code/proteincrawler/id_crawler.py in <module>()
----> 1
2
3
4
5
TypeError: can only concatenate list (not "str") to list
So, the + operators in '+=' and '+' are different.
But I think they should be the same, because they are all plus
Am I wrong or something happens behind the scene开发者_运维技巧?
This is explained here. Copied from the link:
It's because the
+=
operator is doing the equivalent of calling theextend
method, which treats its argument as a generic sequence, and doesn't enforce type.
精彩评论