HomeSearch

Python In Examples: Strings, Lists

This Python 3 article uses the in operator to test strings, list and other collections. It uses not-in to test for nonexistence.

In operator.

Matter is composed of atoms. Strings, and collections, too contain smaller elements. Strings contain substrings, characters. Lists have elements.

With in,

a built-in operator, we search strings and collections. Often these searches are the most efficient. The code is clear and readable and short.

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.

If: This example also combines the "in" and "not in" operators with if-statements. We print True if the expressions are True.

If
Python 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

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.
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

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.
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

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.
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

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, get
Python 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

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
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

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.List, index

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.find

String in, find benchmark.

Usually, "in" is faster than alternative methods. Here I test "in" against the find() method on a string. In operates several times faster than find.

Caution: In still has a cost. Consider using a dictionary for a situation where frequent lookups occur and performance is important.

Hash: A dictionary uses hash codes. These are values computed based on a lookup key. They help make the search for a value faster.

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

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

A review.

In searches for a match within a string or collection (like list, set, dictionary, tuple). It is often the fastest option for search. Its syntax is clear and easy to read.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.