# More Python trivia

Given a set `a`, what’s the difference between:

```a |= set([1])
```

and:

```a = a | set([1])
```

?

## 9 thoughts on “More Python trivia”

1. anonymous says:

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. spizzy says:

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. egometry says:

Do they use different internal methods to get their results?

4. sufianrhazi says:

__ior__
vs
__or__

The former is done in place, fancy that.

5. aegisknight says:

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!)

6. enno says:

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

```>>> a = set([1])
>>> b = a
>>> a = a | set([2])
>>> b
set([1])
>>> a
set([1, 2])
>>> c = b
>>> c |= set([3])
>>> c
set([1, 3])
>>> b
set([1, 3])
```
7. enno says:

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.

8. thespeedbump says:

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])

9. timothyfitz says:

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”