[Tutor] Question about equality of sets
Steven D'Aprano
steve at pearwood.info
Sat Apr 5 20:15:40 CEST 2014
On Sat, Apr 05, 2014 at 12:46:19PM -0500, Jim Byrnes wrote:
> Ubuntu 12.04 python 3.3
>
> I was working through an exercise about sets. I needed to find the
> duplicates in a list and put them in a set. I figured the solution had
> to do with sets not supporting duplicates. I finally figured it out but
> along the way I was experimenting in idle and got some results I don't
> understand.
>
> >>> s = {1,2,3}
> >>> s
> {1, 2, 3}
> >>> s.add(1) == s # <1>
> False
> >>> s.add(1) == s.add(2) # <2>
> True
> >>>
>
> Neither <1> or <2> changes s, so why is <1> False and <2> True ?
You're making an assumption about what s.add returns. You're assuming it
returns a new set. It doesn't. Try this:
print(s.add(100))
and see what it prints.
set.add modifies the set in place. So calling s.add(1) tries to change
s, it doesn't create a new set. It is standard in Python that methods
that change the object in place normally return None:
list.append
set.add
list.sort
list.reverse
dict.update
etc. So your examples try:
None == s # this is false
None == None # but this is true
--
Steven
More information about the Tutor
mailing list