pythonhashset

Any reason there is no returned value from `set.add`?


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

Solution

  • >>> 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.