Python: &= operator
28,004
Solution 1
&=
(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;
}
Solution 2
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.
Solution 3
Copy the set by value instead of by refrerence
tmp = set(s1)
(As s1
is an instance of set
)
Related videos on Youtube
![OhMyGosh](https://i.stack.imgur.com/lH5Uj.png?s=256&g=1)
Author by
OhMyGosh
Updated on July 09, 2022Comments
-
OhMyGosh almost 2 years
When I try to or/and two sets using
&=
and|=
operator, I got some weird result.s1 = {1,2,3} s2 = {2,3,4} tmp = s1 tmp &= s2
As expected, tmp will be {2,3}, but I don't know why
s1
also changed it value to {2,3}.However, if I do:
tmp = tmp & s2
Then,
s1
will be unchanged! Can anyone explain for me what happens underneath&=
operator?-
SomethingSomething over 9 yearsYou should copy
s1
by value and not by reference
-