Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: &= operator

Tags:

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?

like image 731
OhMyGosh Avatar asked Feb 08 '15 15:02

OhMyGosh


People also ask

What is Python used for?

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.

Can I use Python with HTML and CSS?

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.

What is A += in Python?

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.

Is Python easy to learn?

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.


2 Answers

&= (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;
}
like image 77
falsetru Avatar answered Oct 08 '22 14:10

falsetru


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.

like image 23
GLHF Avatar answered Oct 08 '22 16:10

GLHF