2
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?

2
  • The only difference that "pop up" from your post is that, in the second plus operator, you didn't assign the result to a variable. That's translate with the operation: print(l+s) and, maybe, this messes up the whole thing. Have you tried yet to assign l+s to a new variable ? Commented Sep 28, 2011 at 7:42
  • 4
    @DonCallisto Completely wrong. Commented Sep 28, 2011 at 7:50

1 Answer 1

7

This is explained here. Copied from the link:

It's because the += operator is doing the equivalent of calling the extend method, which treats its argument as a generic sequence, and doesn't enforce type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.