2

I saw someone wrote an interesting python line online, but couldn't understand why it works. So we can try the following lines in python interpreter:

s=[1]
s=s+(1,-1)

This will result in an error "TypeError: can only concatenate list (not "tuple") to list". But if done in another way:

s=[1]
s+=(1,-1)

will result in s = [1,1,-1]

So I used to thought x=x+y is equivalent to x+=y, can someone tell me how they are different and why the second way works? Thanks in advance.

1
  • The first duplicate doesn't answer this - it asks why += changes the list. The 2nd is more applicable, though the only real attempt to explain why is something to do with symmetry. Commented Jun 14, 2015 at 20:14

1 Answer 1

1

Instead of += use list.extend:

s = [1]
s.extend((1,-1))
Sign up to request clarification or add additional context in comments.

2 Comments

Your answer's not that far off. It looks like s += ... is implemented as s.extend(tuple(...)) (or v.v). s += 1,-1 works.
The prime questions are "can someone tell me how they are different and why the second way works?". The OP would like to understand (I saw someone wrote an interesting python line online, but couldn't understand why it works), not being provided another solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.