9 thoughts on “More Python trivia”

  1. I don’t know. I cheated and tested it out, but I couldn’t see any difference in the resulting set a. Is one faster or something?

    -Tyler S.

  2. As someone who doesn’t know Python all that well, what is the difference?

    I tried on the command line and seemed to to get the same result.

  3. Ding ding ding. (This bit me as I had a recursive loading dependencies, detecting cycles with a set. I assumed |= would expand out to s = s | t, like the += operator with integers*. Oops.)

    (* More trivia: i += 1 is not an atomic operation in CPython, but list.append is!)

  4. I immeidately guessed it, though probably would have fallen for it myself:

    >>> a = set([1])
    >>> b = a
    >>> a = a | set([2])
    >>> b
    >>> a
    set([1, 2])
    >>> c = b
    >>> c |= set([3])
    >>> c
    set([1, 3])
    >>> b
    set([1, 3])
  5. By the way, this is *exactly* why I still like good old C above all the other languages I write in. Every allocation made is one that I intended.

  6. Funny corner cases like this make me think that set() should perhaps not overload operators quite so liberally.

    The implementations of < and > are also counterintuitive:
    assert not set([1]) > set([2])
    assert not set([1]) < set([2])

  7. Is this really surprising? (Or have I been drinking the kool-aid so long that I forget what plain water is?)

    Immutable types implement a += b as a = a + b, while mutable types make the operation in-place.

    In place:
    a = range(5)
    a += [6]

    New instance:
    a = “five”
    a += “six”

Leave a Reply

Your email address will not be published. Required fields are marked *