Search code examples
pythonpython-3.x

Is there an add-element-to-a-set method returning whether the element was actually added?


I would like to achieve in Python the following semantics which is present in Kotlin:

myset = set()
for elem in arr:
  if not myset.add(elem): return 'duplicate found'

I am looking for a way to get a slight performance boost by 'hijacking' add-to-set operation by analysing the returned value. It should be better if compared to the following approach I already know in Python:

myset = set()
for elem in arr:
  if elem in myset: return 'duplicate found'
  myset.add(elem)

Yet as far as I can observe add() method of set returns None no matter what the outcome of adding is.

Is there such a method in Python3? Looking into the documentation I have not managed to find such a result returning add-to-set method yet.


Solution

  • No, and it has been rejected.