Think Python for CS114

Chapter 22 The in operator

The word in is a boolean operator that takes a value and a sequences and returns True if the first appears in the second.

22.1 With strings

>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False

For example, the following function prints all the letters from word1 that also appear in word2:

def in_both(word1: str, word2: str) -> None:
    for letter in word1:
        if letter in word2:
            print(letter)

With well-chosen variable names, Python sometimes reads like English. You could read this loop, “for (each) letter in (the first) word, if (the) letter (appears) in (the second) word, print (the) letter.”

Here’s what you get if you compare apples and oranges:

>>> in_both('apples', 'oranges')
a
e
s

For strings, in indicates if a value appears as a substring:

>>> 'hop' in 'cheese shop'
True
>>> 'jump' in 'cheese shop'
False

22.2 on lists

The in operator also works on lists.

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False

It will also work with other kinds of sequences.