Reputation: 733
I want to know what are the best practices between using the in tuple
and the in list
conditions and know why, as the following scenario:
my_variable = 'A'
if my_variable in [2, 'A', None]:
return True
elif my_variable in (2, 'A', None):
return True
And if possible list the advantages/disadvantages of tuples/lists in this case.
Upvotes: 3
Views: 668
Reputation: 11
The difference in runtime is negligible between List, Tuple, and Set if there are only 3 elements.
Pep8 style guide doesn't say anything about this as far as I know, so you can use whichever you prefer.
Something the other answers missed, as far as readability goes, is you can declare a set directly like this:
if my_variable in {2, 'A', None}:
print(True)
Upvotes: 1
Reputation: 81664
list
and tuple
both have an O(n) time complexity for x in container
checks.
However, set
have an O(1) for this check (most of the time, the worst case scenario will have a worse time complexity due to hash collisions).
See these timings for a list, tuple and a set with 1 million elements:
from timeit import Timer
li = list (range(1, 1000000))
t = tuple(range(1, 1000000))
s = set (range(1, 1000000))
def x_in_list():
999999 in li
def x_in_tuple():
999999 in t
def x_in_set():
999999 in s
print(min(Timer(x_in_list).repeat(5, 5)))
print(min(Timer(x_in_tuple).repeat(5, 5)))
print(min(Timer(x_in_set).repeat(5, 5)))
Outputs
0.08769642199999961
0.09637485699999981
9.329999999252436e-07
Upvotes: 4
Reputation: 20500
A tuple
is an immutable sequence, whereas a list
is a mutable sequence, which means tuples can't be changes, but list can be.
If you don't want to modify the data structure you are checking in
, use tuple
, else use list, otherwise both behave the same.
my_variable = 'A'
if my_variable in [2, 'A', None]:
print(True)
if my_variable in (2, 'A', None):
print(True)
The output will be
True
True
Note that both list and tuple have O(n)
time complexity to check, to get an average O(1)
complexity, use a set.
if my_variable in set([2, 'A', None]):
print(True)
#True
Upvotes: -1