[Tutor] How is "set(ls).add('a') evaluated? [Was: Re: A program that can check if all elements of the list are mutually disjoint]

boB Stepp robertvstepp at gmail.com
Sat Jun 5 22:19:18 EDT 2021


Ah, I finally see the light, dn!

On Sat, Jun 5, 2021 at 9:08 PM boB Stepp <robertvstepp at gmail.com> wrote:
>
> On Sat, Jun 5, 2021 at 8:57 PM David <bouncingcats at gmail.com> wrote:
> >
> > On Sun, 6 Jun 2021 at 11:37, boB Stepp <robertvstepp at gmail.com> wrote:
> >
> > > I have not played around with set's methods and operators to date, so
> > > while trying to understand this code I tried out different things in
> > > the interpreter.  Along the way I tried something and it surprised me:
> > >
> > > Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928
> > > 64 bit (AMD64)] on win32
> > > Type "help", "copyright", "credits" or "license" for more information.
> > > >>> ls = ["amba", "Joy", "Preet"]
> > > >>> z = set(ls).add('a')
> > > >>> z
> > > >>> print(z)
> > > None           # This surprised me.  I was expecting {'amba', 'Joy',
> > > 'Preet', 'a'}.
> >
> > The set() object has an add() method that modifies
> > its object and returns None.
>
> I understand this.  But for "set(ls).add('a')" I am thinking the
> following sequence of events occur:
>
> 1)  "set(ls)" creates the set-type object "{'amba', 'Joy', 'Preet'}.
> 2)  ".add('a')" method is called on this set object, resulting in the
> new set object "{'amba', 'Joy', 'Preet', 'a'}
> 3)  "z" is now assigned to point to this resultant object.

(3) is *not* correct.  "z" is assigned to what the add() method is
returning, dn's point.

> >>> zz = set(ls).union('a')
> >>> zz
> {'amba', 'Joy', 'Preet', 'a'}
>
> Why are these different in their results?

Here according to the docs the union() method:

"Return a new set with elements from the set and all others."

Caught up in something elementary once again.  Sigh!

boB Stepp


More information about the Tutor mailing list