You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When testing for membership in a static sequence, prefer a set literal over a list or tuple, as Python optimizes set membership tests.
This optimization isn't significant when using literals—while sets do have faster membership checks, doing 1 in (1, 2, 3) is faster than 1 in {1, 2, 3} as it takes 4–5x as much time to just construct a set compared to a tuple (see benchmarks below).
Benchmarks
Creating an object with elements 1, 2, 3
Version
tuple
set
list
tuple vs set
list vs set
3.12
10.28ns
48.71ns
42.37ns
+374%
+15%
3.11
8.24ns
39.88ns
25.55ns
+384%
+56%
3.10
7.98ns
40.73ns
26.86ns
+410%
+52%
3.9
8.73ns
40.00ns
26.03ns
+358%
+54%
3.8
9.43ns
39.84ns
27.38ns
+322%
+46%
Checking whether 1 is a member of the object (w/ a literal)
Version
tuple
set
list
tuple vs set
list vs set
3.12
15.19ns
16.54ns
15.20ns
+9%
+9%
3.11
13.47ns
14.74ns
14.14ns
+9%
+4%
3.10
13.83ns
15.20ns
13.83ns
+10%
+10%
3.9
15.66ns
16.94ns
15.61ns
+8%
+9%
3.8
17.83ns
19.00ns
17.81ns
+7%
+7%
Therefore (even though the difference isn't that substantial) I think it would make more sense for the rule to suggest
using a tuple when checking against a literal, e.g. 1 in (1, 2, 3), and
using a set when checking against a constant, e.g. S = {1, 2, 3}; 1 in S (although I suspect literals may be faster than constants for small objects (because of variable lookup?), in which case tuples would be the way).
Hopefully I haven't made any mistakes with my reasoning 😄
The text was updated successfully, but these errors were encountered:
From the docs:
This optimization isn't significant when using literals—while
set
s do have faster membership checks, doing1 in (1, 2, 3)
is faster than1 in {1, 2, 3}
as it takes 4–5x as much time to just construct aset
compared to atuple
(see benchmarks below).Benchmarks
Creating an object with elements
1, 2, 3
Checking whether
1
is a member of the object (w/ a literal)Therefore (even though the difference isn't that substantial) I think it would make more sense for the rule to suggest
tuple
when checking against a literal, e.g.1 in (1, 2, 3)
, andset
when checking against a constant, e.g.S = {1, 2, 3}; 1 in S
(although I suspect literals may be faster than constants for small objects (because of variable lookup?), in which case tuples would be the way).Hopefully I haven't made any mistakes with my reasoning 😄
The text was updated successfully, but these errors were encountered: