sentinel value
A sentinel value is a special value that an algorithm treats as a signal rather than as ordinary data, most often to mark the end of a sequence or to terminate a loop. Its defining requirement is that it stay distinct from every legitimate value the data can take, so a reading loop can check each value and stop the moment the sentinel appears:
Sentinels carry meaning in-band, inside the data stream itself, which lets code detect a boundary when no separate length or count is available.
Common Python examples include the empty string that readline() returns at the end of a file, a sentinel object placed on a queue.Queue to signal that no more items are coming, and a stop word that ends an input loop.
The technique breaks down when no value can be spared as the signal, which leads to the semipredicate problem: the sentinel collides with a legitimate result, so code can no longer tell a signal from real data. That risk is why many languages prefer out-of-band signaling through option types, exceptions, or a unique marker object.
In Python, calling object() produces a guaranteed-unique sentinel, and since Python 3.15 the built-in sentinel() creates unique sentinel objects with a readable representation.
Related Resources
Tutorial
Python Sentinel Values: Using the New sentinel Built-in
Learn how to create a Python sentinel value with the new built-in in Python 3.15 and get readable signatures, type hints, and safe copying and pickling.
For additional information on related topics, take a look at the following resources:
- Null in Python: Understanding Python's NoneType Object (Tutorial)
- Python while Loops: Repeating Tasks Conditionally (Tutorial)
- Python for Loops: The Pythonic Way (Tutorial)
- Python's map(): Processing Iterables Without a Loop (Tutorial)
- Iterators and Iterables in Python: Run Efficient Iterations (Tutorial)
- The Walrus Operator: Python's Assignment Expressions (Tutorial)
- How to Iterate Through a Dictionary in Python (Tutorial)
- Python 3.15 Preview: Sentinel Values (Quiz)
- Python's None: Null in Python (Course)
- Null in Python: Understanding Python's NoneType Object (Quiz)
- Mastering While Loops (Course)
- Python while Loops: Repeating Tasks Conditionally (Quiz)
- For Loops in Python (Definite Iteration) (Course)
- Python for Loops: The Pythonic Way (Quiz)
- Python's map() Function: Transforming Iterables (Course)
- Efficient Iterations With Python Iterators and Iterables (Course)
- Iterators and Iterables in Python: Run Efficient Iterations (Quiz)
- Python Assignment Expressions and Using the Walrus Operator (Course)
- The Walrus Operator: Python's Assignment Expressions (Quiz)
- Python Dictionary Iteration: Advanced Tips & Tricks (Course)
- Python Dictionary Iteration (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.