[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 21:35:50 EDT 2021
As is often the case Mr. Singh's query got me to play around in the interpreter.
On Sat, Jun 5, 2021 at 8:10 AM Manprit Singh <manpritsinghece at gmail.com> wrote:
> ls = ["amba", "Joy", "Preet"]
> for idx, ele in enumerate(ls):
> if idx < len(ls)-1:
> if not all(set(ele).isdisjoint(ch)for ch in ls[idx+1:]):
> print("Not mutually disjoint")
> break
[...]
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 "normal" way of using the add() method works fine:
>>> z = set(ls)
>>> z
{'amba', 'Joy', 'Preet'}
>>> z.add('a')
>>> z
{'amba', 'Joy', 'Preet', 'a'}
But the following works which is in a similar chained format:
>>> zz = set(ls).union('a')
>>> zz
{'amba', 'Joy', 'Preet', 'a'} # BTW, please forgive bad identifier naming!
So I am *not* understanding how "set(ls).add('a')" is evaluated to
result in "None".
TIA!
boB Stepp
More information about the Tutor
mailing list