Pythonic way to set.add() or set.update() with a return for passing as an arg?

Question:

In Python, naturally set.add() and set.update() do not return the modified set. However, if I want to pass a modified version of an existing set as an arg in say a recursive function it seems I have to create a temporary set: The following seems cumbersome.

temp_set = set([an_element])
temp_set.update(an_existing_set)
foo(temp_set)

Is there no single line trick for this? Adding and returning in a single statement?
Note I specifically do not want to modify the existing set in place.

foo(set([an_element].addAndReturn(an_existing_set))

I suppose the answer might just be "pass the new elem/set along with the old and combine them in place after the recursive call", but I am unsatisfied with this limitation.

Asked By: Mister Nibbles

||

Answers:

foo(an_existing_set | {an_element})

Just use the set union operator.

There’s also a method form, union:

foo(an_existing_set.union({an_element}))
Answered By: user2357112
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.