For some reason there is no return value from set.add

Current, since the return value from set.addalways None. I have to do the following.

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

It would be nice if I could

if not s.add(1):
    print 'already found'
    return
+3
source share
2 answers
>>> 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 collection, just add a value to it. You cannot 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 there is 1 in the set, then if 1 in s.

+8
source

For some reason there is no return value from set.add

Yes.

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

, . .

, pop.

+2

Source: https://habr.com/ru/post/1775777/


All Articles