1

I'm working on LeetCode 78. Subsets and found this interesting error. If I change the marked line to the commented line, such an error will be thrown out.

My function

I announced "res" in the outer function, why is res.append() different from res += ? I know += is more like .extend() but that is not the conflict here. What caused the reference error?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
Noam
  • 11
  • 1
  • This ia a duplicate https://stackoverflow.com/questions/725782/in-python-what-is-the-difference-between-append-and – dir Jul 23 '21 at 03:30
  • @dir No it is not. So the answer to your question: `.append()` will mutate the existing object `res` is pointing to while `+=` will create a new, local variable named `res`. That's why you are getting the error because Python thinks that (the second) `res` is a local variable, but you can't `+=` to it because it hasn't been assigned before within that function. – Selcuk Jul 23 '21 at 03:31
  • Interesting. If you have both of them together, then `append` starts to throw error too. – Chris Jul 23 '21 at 04:14

1 Answers1

0

Of course it will throw an error. +=1 only applies to One number, whether it being an integer or a float or a decimal. The fact that python do not force you to declare the type of a variable does not mean that you can apply the method of one type to another on your own imagination. And append is restricted to lists, applying it to a number you will also get an error.

George Y
  • 525
  • 3
  • 14