Python: &= operator

&= (set.__iadd__) for set is implemented differently with & (set.__add).

set &= ... is implemented using set.intersection_update which update the set in-place.


Relevant CPython code (Object/setobject.c):

set_iand(PySetObject *so, PyObject *other)
{
    PyObject *result;

    if (!PyAnySet_Check(other))
        Py_RETURN_NOTIMPLEMENTED;
    result = set_intersection_update(so, other); // <----
    if (result == NULL)
        return NULL;
    Py_DECREF(result);
    Py_INCREF(so);
    return (PyObject *)so;
}

It's called intersection_update. return set s keeping only elements also found in t. As you see in this picture;

enter image description here

You are re-building first set with intersection.