Skip to main content

Section 8.7 Sequence Conditional Operators

Along with basic comparsion operators, Python also provides built-in operators to create boolean expressions with sequences, such as strings and lists.
The in operator tests if one string is a substring of another:
Note that a string is a substring of itself, and the empty string is a substring of any other string. (Also note that computer scientists like to think about these edge cases quite carefully!)
The not in operator returns the logical opposite result of in.

Subsection 8.7.1 List Membership

in and not in are boolean operators that test membership in a sequence. We used them previously with strings and they also work here.
Remember that in and not in only checks for membership in the top level of a list.
Check your understanding

Checkpoint 8.7.1.

What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(3.14 in alist)
  • True
  • Yes, 3.14 is an item in the list alist.
  • False
  • There are 7 items in the list, 3.14 is one of them.

Checkpoint 8.7.2.

What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(57 in alist)
  • True
  • in returns True for top level items only. 57 is in a sublist.
  • False
  • Yes, 57 is not a top level item in alist. It is in a sublist.

Checkpoint 8.7.3.

Create one conditional to find whether β€œfalse” is in string str1. If so, assign variable output the string β€œFalse. You aren’t you?”. Check to see if β€œtrue” is in string str1 and if it is then assign β€œTrue! You are you!” to the variable output. If neither are in str1, assign β€œNeither true nor false!” to output.
You have attempted of activities on this page.