[Python-ideas] set.add() return value
Ralf W. Grosse-Kunstleve
rwgk at yahoo.com
Thu Feb 12 23:19:03 CET 2009
Has this come up before?
Python 2.6.1 behavior:
>>> s = set()
>>> print s.add(1)
None
>>> print s.add(1)
None
>>>
Desired behavior:
>>> s = set()
>>> print s.add(1)
True
>>> print s.add(1)
False
>>>
Motivation:
Instead of
if (1 not in s): # O(N log N) lookup
s.add(1) # O(N log N) lookup again
do_something_else()
or
prev_len = len(s)
s.add(1) # O(N log N) lookup
if (len(s) != prev_len):
do_something_else()
one could write
if (s.add(1)):
do_something_else()
which would be as fast as the second form and the most concise of all alternatives.
More information about the Python-ideas
mailing list