value = "cat"# See if the value exists in the tuple.
if value in ("dog", "bird", "cat"):
String in, find benchmark. Usually, "in" is faster than alternative methods. As a Python developer, we should use "in" when possible as it is clear, easy to read, and fast.
Version 1 This version of the code uses "in" on a string. It makes sure the testis correct.
Version 2 Here we test the find method on a string. Logically this version of the code does the same thing as version 1.
Result In operates several times faster than find. Consider using a dictionary for a situation where frequent lookups occur.
value = "characters"
# Version 1: use "not in."for i in range(0, 1000000):
if "t" not in value:
# Version 2: use find method.for i in range(0, 1000000):
if value.find("t") == -1:
1406834210.259137 in = 0.125 s
1406834210.696638 find = 0.437 s
Index, list. Often with lists, we need to locate a specific element and its index. The "in" operator does not work here. We can use "index" or a simple for-loop to do the search.