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;
You are re-building first set with intersection.
Copy the set by value instead of by refrerence
tmp = set(s1)
(As s1
is an instance of set
)