Good day.

I am learning Python by video lectures, I have reached sets, the example mentions the union method

a.union 

and

 a.update 

What is the fundamental difference?

    1 answer 1

    union as a result returns a new set without changing the source, and update returns nothing, but adds elements of the second to the first set.

     >>> a = set([1,2,3]) >>> b = set([2,3,4]) >>> print a.union(b) set([1, 2, 3, 4]) >>> print a set([1, 2, 3]) >>> print b set([2, 3, 4]) >>> a = set([1,2,3]) >>> b = set([2,3,4]) >>> print a.update(b) None >>> print a set([1, 2, 3, 4]) >>> print b set([2, 3, 4]) 
    • That is, when creating (union) a new set, an additional memory is allocated? and with (update) get less memory consumption? - nisa
    • I'm not ready to answer what exactly happens in the interpreter, but most likely it is. When creating a new set with the help of the union, a new object will be created exactly and will take up memory. - LinnTroll pm