[Python-ideas] set.add() return value

Raymond Hettinger python at rcn.com
Thu Feb 12 23:40:02 CET 2009

[Ralf W. Grosse-Kunstleve]
> Instead of
>  if (1 not in s): # O(N log N) lookup
>    s.add(1) # O(N log N) lookup again
>    do_something_else()

Three thoughts:
* insertion and lookup times are O(1), not O(n log n).
* because of caching the second lookup is very cheap.
* the bdfl frowns on mutating methods returning anything at all

>  if (s.add(1)):
>    do_something_else()

I would find this to be useful but don't find it to be
a significant improvement over the original.  Also,
I find it to be a bit tricky.  Currently, sets have a nearly
zero learning curve and are not imbued with non-obvious
behaviors.  The proposed form requires that the reader
knows about the special boolean found/notfound behavior.
Also, since some people do want mutating methods to
return a copy of the collection (i.e. s.add(1).add(2).add(3)),
those folks will find your suggestion to be counter-intuitive.


More information about the Python-ideas mailing list