10

Current, since the returned value from set.add is always None. I have to do the following.

if 1 in s:
    print 'already found'
    return
s.add(1)

Would it be nice if I can

if not s.add(1):
    print 'already found'
    return
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • Agreed, I don't understand why this behavior would be good by default. You can always define a function to do this (after all, what are functions for?) – Rafe Kettler Nov 19 '10 at 04:11
  • 11
    It's useful, because it avoids having to do two hash lookups; search and insert can be done together, with a single `__hash__` call and a single hash table search. I don't think there's actually any meaningful question being asked here, though... – Glenn Maynard Nov 19 '10 at 04:19
  • Just subclass `set` and [add the desired behaviour](http://stackoverflow.com/a/30318487/1307905) – Anthon May 19 '15 at 06:47

2 Answers2

7
>>> None == False
False
>>> None == True
False
>>> None == None
True
>>> not None
True

If s.add always returns None, then your condition will always be True. But since s is a set, just add the value to it. You can't have duplicate values in a set, by definition :

>>> a = set()
>>> a.add(1)
>>> a
{1}
>>> a.add(1)
>>> a
{1}

If you just want to know if 1 is in the set, then do if 1 in s.

unholysampler
  • 17,141
  • 7
  • 47
  • 64
Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
4

Any reason there are no returned value from set.add

Yes.

The reason is that collection mutators, like set.add(), list.append(), etc., never return a value.

If a method mutates and object, it does not return a value. That's the rule.

There are minor exceptions, like pop.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • 6
    That's a horrible reason. What I mean is, you give the reason as to why it doesn't have a return value to be that would be against the rule, yet there are exceptions to the rule. Why can't this be another exception? It could have returned if the element already existed or not. – Horse SMith Feb 28 '14 at 05:53
  • Sure, but I think for that, you'd have to open up a new question on SO and discuss that there. In short, i believe it's convention and whether or not that is the best logic is up for debate. – Miguel Diaz Oct 24 '16 at 16:38