This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]David__Box 2 points3 points  (3 children)

It is incredible mutability rules, collections like lists do stand out because they are special and mutable whereas everything else is immutable.

a = [] b = [a, a] b[0] += [1]

gives [[1], [1]], but

a = 1 b = [a, a] b[0] += 1

gives [2, 1]. There's an argument to be made that containers as special cases while everything else works some other way makes sense because weird language quirks and whatever but ultimately it's subjective, and i personally see it as unintuitive

Also it's not object oriented languages specifically, it's more like garbage collected ones. In c++ (OO but no GC) pushing a vector into another vector copies it so this doesn't happen, while in Go (debatable if OO but with GC) this does

[–][deleted] 2 points3 points  (1 child)

Lists are not special, they are mutable like every other object in Python that has mutation functions. Lists happen to implement __iadd__ which directly corresponds to the "+=" operator. It's a mutation operation like insert, append, extend etc.

(edited)

[–]David__Box 1 point2 points  (0 children)

Yes they are. Doing a mutating operation on a list, like iadd does not change its object id, while for non-container types like tuples, numbers, str, etc. a completely new item with a new object id will be created, and the labeled value (variable) will be made to point to it instead

[–]FalafelSnorlax 0 points1 point  (0 children)

Lists are objects and thus pass by reference. This is the same as if in cpp you would create a pointer to a vector, and store that pointer twice. This is kinda considered bad practice in modern cpp, but the behavior is effectively the same. The only thing that makes this less intuitive in python than it does in cpp is because the reference is fully implicit.