Suppose a program needs to search a list S for a negative number. It could be that S doesn't have a negative number, it could be that -200 is the first item, or even that S consists entirely of -1's. A well-written program needs to take care of all these possibilities. The method described in the chapter is to write a loop, then have an if-statement in the body of the loop that tests for the search criterion When a suitable item is found, then perhaps a break statement or an early return can be used to quickly end the loop.

In special circumstances, there is another method, called the sentinel technique. Suppose we somehow know that some particular negative number, say -9999, cannot be in S. Then the following code searches S for the first negative number, returning -9999 in case S does not have any negative number.

1
2
3
4
def findNeg(S):
  for item in S+[-9999]:
    if item < 0:
      return item 

The trick is that the expression S+[-9999] is guaranteed to have at least one negative number. That means the loop will end, at some point, by the "return item" statement.

The sentinel technique is not so useful in Python. In lower-level language, like C, data structures like lists and dictionaries are not built-in. Programs need to implement these structures. Some further discussion is found here.