C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
If: This example also combines the "in" and "not in" operators with if-statements. We print True if the expressions are True.
IfPython program that uses in, not in, strings
value = "abc"
# There is a "c".
if "c" in value:
print(True)
# There is no "x".
if "x" not in value:
print(True)
Output
True
True
Python program that finds substrings
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)
Output
1
2
Python program that shows in return value
elements = [10, 20, 30]
# This evaluates to true.
result = 20 in elements
print(result)
# False.
result = 40 in elements
print(result)
Output
True
False
Python program that uses in, list
animals = ["cat", "dog", "bird"]
# There is a dog.
if "dog" in animals:
print(True)
# There is no fish.
if "fish" not in animals:
print(True)
Output
True
True
Note: For dictionaries, more complex lookup methods, like get() may be needed more often than "in."
Dictionary, getPython program that uses 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)
Output
1
2
Python program that uses in, tuple
value = "cat"
# See if the value exists in the tuple.
if value in ("dog", "bird", "cat"):
print(True)
Output
True
Version 1: This version of the code uses "in" on a string. It makes sure the test is 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.
Python program that times in, find
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())
Output
1406834210.134138
1406834210.259137 in = 0.125 s
1406834210.696638 find = 0.437 s