LarsVegas
LarsVegas

Reputation: 6832

Python: check membership or just use add with set

Should I rather check if an element is already present in a set or just use add() anyhow?

So better do

uniq = set()
_ = [uniq.add('%s %s' % (k,hn)) for hn in v if '%s %s' % (k,hn) not in uniq ]

Or better:

uniq = set()
_ = [uniq.add('%s %s' % (k,hn)) for hn in v]

Is there an advantage choosing one approach over the other?

Upvotes: 0

Views: 287

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123940

There is no point in testing membership if all you are doing is adding values. You are doing extra work the .add() method already does for you.

You should never use a list comprehension for the side effects; you created a list object full of None references, then discard it again. A simple for loop would have been far more efficient and better to understand and maintain.

In this case, you don't need to call set.add() in a loop even, just use set.update() with a generator expresion:

uniq = set()
uniq.update('%s %s' % (k,hn) for hn in v)

where uniq is presumably an existing set simplified down to an example. If not, you could use a set comprehension to create your set from scratch, using one line of code:

uniq = {'%s %s' % (k,hn) for hn in v}

Upvotes: 1

Related Questions