Performance: in is better
timeit.timeit("pub='1'; pub == 1 or pub == '1'")
0.07568907737731934
timeit.timeit("pub='1'; pub in[1, '1']")
0.04272890090942383
timeit.timeit("pub=1; pub == 1 or pub == '1'")
0.07502007484436035
timeit.timeit("pub=1; pub in[1, '1']")
0.07035684585571289
#other options
timeit.timeit("pub='1'; pub in (1,'1')")
0.04643988609313965
timeit.timeit("pub='1'; pub in {1,'1'}")
0.17076611518859863
timeit.timeit("pub=1; pub in (1,'1')")
0.047419071197509766
timeit.timeit("pub=1; pub in {1,'1'}")
0.1770930290222168
So, {} > or > [] > ()
based on performance.
Practice: in
is preferred as it is less to type. (), [], {}
equally good based on practice
Memory:
sys.getsizeof([1,"1"])
88
sys.getsizeof("1",1)
38
#other options
sys.getsizeof(("1",1))
72
sys.getsizeof({"1",1})
232
So, {} > [] > () > or
based on memory
Although not asked,, good to know:
Functionality: Value equality and not reference equality
in
is just sequential checking equality ==
. So similar. in
uses ==
and not is
.
What I mean to say is this:
>>> a = [1,2,3]
>>> b = [1,a]
>>> b
[1, [1, 2, 3]]
>>> 1 in b
True
>>> a in b
True
>>> [1,2,3] in b
True
So it is implemented not like this:
>>> for i in b:
... print [1,2,3] is i
...
False
False
is
will return True if two variables point to the same object, ==
if the objects referred to by the variables are equal. in
uses ==