On 04/05/2014 01:15 PM, Steven D'Aprano wrote:
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.
Actually my assumption was worse than that. I was thinking that because
it would not add a dup it would end up being {1,2,3} == {1,2,3}
completely forgetting that the left side would return None.
Thanks, Jim
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
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor