top | item 47065403

(no title)

maxnoe | 11 days ago

But this exact example is different, because the critical step of mutation is missing.

The initial line is the same, but:

    a = b = random.random()
    a += 1
    a == b # False
Only because floats are immutable and thus an implicit copy is made and lists are mutable so the same mutable instance is pointed to by both names.

This talk still applies despite its age: https://youtu.be/_AEJHKGk9ns?si=q5HjMOM9QS3_bFzH

discuss

order

jp57|10 days ago

But the semantics of python is that variables contain references to lists and lists are mutable while constants are not.

jibal|9 days ago

You seem to have forgotten the point of your comment, which was to offer an analogous case where surely one wouldn't expect two different values ... but the fact that lists have reference semantics and numbers (not just "constants") have value semantics (that's the issue, not mutability--variables containing numbers are mutable in Python--they don't contain a reference to an unmutable number ... numbers are always copied into the cell) makes all the difference in the world. If one actually does analogize from your example, then one might well expect changing a to not change b since it doesn't in your example ... they might not realize that lists have reference semantics and thus think that a = b = [] copies an empty list to a and copies an empty list to b. That's how it works in Perl with `@a = @b = ();` ... changing @a does not change @b.

On top of all that, the OP made clear in the first paragraph that they didn't have the expectation that you ascribed to them ... they did understand that [] has reference semantics and changing a changes b all along ... but they apparently occasionally have a lapse in their mental model where they forget that (or perhaps they introduced the bug by naively/blindly converting some Perl code ... I've seen that happen.)

I won't offer corrections of additional errors or respond further in any other way.