With "in," a built-in Python operator, we search strings and collections. Often these searches are the most efficient. The code is clear and readable and short
.
The for
-loop also uses an "in" keyword, but this one has a different meaning. It is just part of the for
-loop, part of the enumeration expression.
string
This operator can search for individual characters within a string
. The quotes used don't matter—we can use single or double
quotes here.
if
-statements. We print True if the expressions are True.value = "abc" # This letter is found. if "c" in value: print(True) # This letter is not found. if "x" not in value: print(True)True True
List
With a list, the "in" operator matches an existing element. If no matching element is found, "in" returns false and "not in" returns true. More than one value cannot be tested.
in
-operator with a "not" keyword to negate the expression. Change "in" to "not in."colors = ["blue", "green"] # Test for blue string. if "blue" in colors: print("BLUE FOUND")BLUE FOUND
We can also search for substrings (or "slices") within strings. The entire substring specified must be found in the correct order. Incomplete matches return False.
value = "cat and dog" # This substring is in the value. if "and" in value: print(1) # This one is not. if "and cat" not in value: print(2)1 2
Most examples show the "in" operator inside an if
-statement. This makes sense. But "in" is just part of an expression that returns True or False—a boolean.
elements = [10, 20, 30] # This evaluates to true. result = 20 in elements print(result) # False. result = 40 in elements print(result)True False
Dictionary
The "in" operator on dictionaries matches just keys. It does not consider the values. And we cannot pass it a tuple (pair) containing both: this does not work.
get()
may be needed more often than "in."lookup = {"snake" : "green", "bird" : "blue"} # Keys are searched with "in": if "bird" in lookup: print(1) # But values are not searched: if "blue" not in lookup: print(2)1 2
Tuple
This operator works well on tuples, with any number of items. We do not need a separate tuple variable for an if
-statement—we can test a tuple specified directly within an if.
value = "cat" # See if the value exists in the tuple. if value in ("dog", "bird", "cat"): print(True)True
String
in, find benchmarkUsually, "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.
string
. It makes sure the testis correct.string
. Logically this version of the code does the same thing as version 1.import time value = "characters" print(time.time()) # Version 1: use "not in." for i in range(0, 1000000): if "t" not in value: raise Exception() print(time.time()) # Version 2: use find method. for i in range(0, 1000000): if value.find("t") == -1: raise Exception() print(time.time())1406834210.134138 1406834210.259137 in = 0.125 s 1406834210.696638 find = 0.437 s
Index
, listOften 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.
String
findWe can use find and rfind to search for a string
from the left or right side. This returns an index. With index()
and rindex, an error is returned if no match is located.
In searches for a match within a string
or collection. It is often the fastest option for search. Its syntax is clear and easy to read.