logoalt Hacker News

jp57today at 4:28 PM2 repliesview on HN

The author's expectations seem strange. Take another example:

    a = b = random.random()
I would not expect a and b to get different values. It would be very strange if using `[]` had different behavior than a function call in the same place. Am I out of step here?

Replies

maxnoetoday at 7:46 PM

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

jibaltoday at 5:50 PM

What expectations? The author states right up front "I've known of this behavior for a long time".

A somewhat trickier example of the same issue is using [] as a default parameter value ... though there are warnings about the problem with that (it's the same list on every call) throughout the documentation.