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