Home
Python
in Keyword
This page was last reviewed on Apr 14, 2023.
Dot Net Perls
In operator. 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.
Shows a list
Another in. 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.
for
In, 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.
Also This example combines the "in" and "not in" operators with if-statements. We print True if the expressions are True.
if
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.
Also We can use the in-operator with a "not" keyword to negate the expression. Change "in" to "not in."
not
Shows a list
colors = ["blue", "green"] # Test for blue string. if "blue" in colors: print("BLUE FOUND")
BLUE FOUND
In, substrings. 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
Returns true, false. 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.
Note For dictionaries, more complex lookup methods, like get() may be needed more often than "in."
Dictionary
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.
Tuple
value = "cat" # See if the value exists in the tuple. if value in ("dog", "bird", "cat"): print(True)
True
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.
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, 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.
String List
String find. We 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.
String find
A review. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 14, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.