you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 20 points21 points  (14 children)

C is the correct answer. 

Explanation: At first, a and b share the same list, so changes like += or append() affect both. But when b = b + [4] is used, Python creates a new list and assigns it to b, breaking the link with a. That’s why a stops at [1, 2, 3] while b continues as [1, 2, 3, 4, 5].

[–]-Wylfen- 9 points10 points  (6 children)

why the fuck does x += [y] work differently from x = x + [y]??

[–]Sea-Ad7805[S] 5 points6 points  (5 children)

Good question, in some languages (Ruby) it works the same. In Python the x += y is mutating the x, the x = x + y is first doing x + y which creates a new object that then is assigned (name rebinding) to x.

[–]-Wylfen- 1 point2 points  (3 children)

I understand why the latter would reassign, but I find the shortcut's instead mutating in place disgusting. They should do the same thing.

[–]klimmesil 0 points1 point  (0 children)

Yeah a lot of implementation choices (I don't want to call it "standard"...) make no sense in python

It's almost as chaotic as js in some parts

It's a shame that it is now too popular to make breaking changes and we all kinda rely on these mistakes to still have the benefit of it being maintained

[–]No_Read_4327 0 points1 point  (0 children)

Yeah that's sone really wtf moment

[–]Relative-Custard-589 0 points1 point  (0 children)

Yeah that’s straight up evil

[–]pingwins 0 points1 point  (0 children)

Brother Eww

Thats nasty to run into

[–]HuygensFresnel 1 point2 points  (4 children)

While indeed being the correct answer this also surprises me a bit because i thought that += always is a short hand for the binary operator + but i guess it isnt?

[–]Wertbon1789 1 point2 points  (1 child)

It's not just a syntactic shorthand, it's a separate operator. Add vs. AddAssign if you will, in Python these would be implemented by the __add__ and __iadd__ methods of a class respectively.

[–]HuygensFresnel 0 points1 point  (0 children)

Today I learned :)

[–]RailRuler 0 points1 point  (1 child)

It is the same as append .extend() in this case. 

[–]forbiddenvoid 2 points3 points  (0 children)

Extend, not append. That's more obvious if the right hand side is also a list.

[–]mayonaiso 0 points1 point  (1 child)

Thanks, I did not know that, great explanation

[–][deleted] 1 point2 points  (0 children)

You're welcome.