Find the first record that violates monotonic order
Also published in our primary archive.
To find the first record that violates monotonic order in Python, compare each source-order timestamp with the timestamp immediately before it and stop at the first decrease. Do not sort first: sorting creates a new ordered view, but it also hides whether the original input arrived out of order.
This fixture has timestamps 01:00, 03:00, then 02:00. The sorted view looks valid, which demonstrates why it cannot diagnose source-order corruption. The next() expression instead enumerates records starting at index 1 and returns the first (index, record) whose timestamp is smaller than its predecessor. It reports index 2.
The input list is not mutated: sorted() returns a separate list, and the detection expression only reads records. This is appropriate when fixed-width, zero-padded HH:MM strings are known to be comparable lexicographically. For timestamps with dates, offsets, non-padded fields, or mixed formats, parse and validate them first; string comparison alone does not establish chronological correctness.
enumerate() supplies the original zero-based index while iterating, and next() returns the first matching generated value. Both are standard built-ins documented by Python. This example uses only longstanding Python 3 features; no newer minimum version is required.
AI assistance disclosure: this article was prepared with AI assistance and checked against the shown synthetic fixture.
Source: Python built-in functions: enumerate() and next().
records = [
{"timestamp": "01:00"},
{"timestamp": "03:00"},
{"timestamp": "02:00"},
]
sorted_records = sorted(records, key=lambda record: record["timestamp"])
violation = next(
(
(index, record)
for index, record in enumerate(records[1:], 1)
if record["timestamp"] < records[index - 1]["timestamp"]
),
None,
)
assert records == [
{"timestamp": "01:00"},
{"timestamp": "03:00"},
{"timestamp": "02:00"},
]
assert violation == (2, {"timestamp": "02:00"})
print("input:", records)
print("sorted first:", sorted_records)
print("first violation:", violation)
input: [{'timestamp': '01:00'}, {'timestamp': '03:00'}, {'timestamp': '02:00'}]
sorted first: [{'timestamp': '01:00'}, {'timestamp': '02:00'}, {'timestamp': '03:00'}]
first violation: (2, {'timestamp': '02:00'})