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?
Python is a computer programming language often used to build websites and software, automate tasks, and conduct data analysis. Python is a general-purpose language, meaning it can be used to create a variety of different programs and isn't specialized for any specific problems.
If you're interested in web development with Python, then knowing HTML and CSS will help you understand web frameworks like Django and Flask better. But even if you're just getting started with Python, HTML and CSS can enable you to create small websites to impress your friends.
The plus-equals operator += provides a convenient way to add a value to an existing variable and assign the new value back to the same variable. In the case where the variable and the value are strings, this operator performs string concatenation instead of addition.
Python is widely considered among the easiest programming languages for beginners to learn. If you're interested in learning a programming language, Python is a good place to start. It's also one of the most widely used.
&=
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With