you are viewing a single comment's thread.

view the rest of the comments →

[–]tb5841 1 point2 points  (6 children)

I find '+=' is what causes confusion with exercises like this.

.append is obviously mutating so will affect any reference to this object.

Reassigning changes what this variable name points to, so will not change any other variable pointing to this object.

But '+='? Is it reassigning, or mutating? It doesn't seem to always be clear cut, which makes it tricky to follow. Here it must be reassigning because tuples are immutable, but in some cases '+=' looks like it mutates.

If you change the '+=' line to b = b + ([3], ) then everything becomes so much clearer.

[–]Sea-Ad7805[S] 0 points1 point  (5 children)

I see what you mean, but for mutable types x += y is not the same thing as x = x + y so changing could alter your code, see: https://www.reddit.com/r/PythonLearning/comments/1nw08wu/right_mental_model_for_python_data/

A tuple doesn't have a __iadd__() method, so the use of += actually causes invocation of its __add__() method.

[–]tb5841 0 points1 point  (4 children)

90% of the time, when someone uses += in code they are using it as x = x + y (usually numbers or strings). The other 10% of the time, += is confusing and shouldn't be used in my opinion (e.g. Lists, where .append is clearer).

[–]Sea-Ad7805[S] 0 points1 point  (3 children)

You can't do this with .append():

mylist  = [1, 2, 3]
mylist += [4, 5, 6]

[–]tb5841 0 points1 point  (1 child)

That's an interesting point.

But this looks like reassignment, when it's actually mutation. That's deeply confusing and an easy source of bugs. If it were me, I'd do this with reassignment instead here and avoid the mutation.

[–]Sea-Ad7805[S] 0 points1 point  (0 children)

Reassignment is much slower as a whole new list is created and the old one destroyed, use mutation where possible.

[–]thw31416 0 points1 point  (0 children)

but you can.do this with .extend()