python - Should I check if an item is already in a set before adding it? -


if foo builtin set know contains "bar", of these faster? more pythonic?

foo.add("bar") 

or

if foo not in bar:     foo.add("bar") 

actually, second may faster (output ipython):

in [2]: %timeit s.add("a") slowest run took 68.27 times longer fastest. mean intermediate result being cached  10000000 loops, best of 3: 73.3 ns per loop  in [3]: %timeit if not "a" in s: s.add("a") 10000000 loops, best of 3: 37.1 ns per loop 

but anyway, the first 1 more pythonic, agree.


Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -