If you want to join n
sets, the best performance seems to be from set().union(*list_of_sets)
, which will return a new set.
Thus, the usage might be:
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {4, 5, 6}
s1.union(s2, s3) # returns a new set
# Out: {1, 2, 3, 4, 5, 6}
s1.update(s2, s3) # updates inplace
Adding to Alexander Klimenko's answer above, I did some simple testing as shown below. I believe the main takeaway is that it seems like the more random the sets are, the bigger the difference on performance.
from random import randint
n = 100
generate_equal = lambda: set(range(10_000))
generate_random = lambda: {randint(0, 100_000) for _ in range(10_000)}
for l in [
[generate_equal() for _ in range(n)],
[generate_random() for _ in range(n)]
]:
%timeit set().union(*l)
%timeit reduce(or_, l)
Out:
# equal sets: 69.5 / 23.6 =~ 3
23.6 ms ± 658 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
69.5 ms ± 2.57 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# random sets: 438 / 78.7 =~ 5.6
78.7 ms ± 1.48 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
438 ms ± 20.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Therefore, if you want to update inplace, the best performance comes from set.update
method, as, performance wise, s1.update(s2, s3) = set().union(s2, s3)
.
|
?|
?def apply_set_operation(a, b, set_operation)
. When calling this function, I'd preferapply_set_operation(a, b, set.union)
toapply_set_operation(a, b, set.__or__)
a | b
instead of calling a function to do that?