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.

Hao
  • 356
  • 2
  • 15
  • 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. – hpaulj Jun 14 '15 at 20:14

1 Answers1

1

Instead of += use list.extend:

s = [1]
s.extend((1,-1))
vaultah
  • 44,105
  • 12
  • 114
  • 143
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • Your answer's not that far off. It looks like `s += ...` is implemented as `s.extend(tuple(...))` (or v.v). `s += 1,-1` works. – hpaulj Jun 14 '15 at 20:07
  • 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. – mins Nov 16 '20 at 13:00