[Tutor] How is "set(ls).add('a') evaluated? [Was: Re: A program that can check if all elements of the list are mutually disjoint]
David
bouncingcats at gmail.com
Sat Jun 5 21:55:53 EDT 2021
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.
It is common style for methods that modify their objects
to return None. The intent of this is to remind users that such methods
act by side effect on an existing object, not by creating a a new object.
More information about the Tutor
mailing list