Partition records into accepted and rejected lists

Partitioning separates one ordered sequence into two ordered outputs according to a predicate. This example receives name-and-score tuples and accepts scores of at least 60. It places ("ada", 88) and ("cy", 73) in accepted, while ("ben", 57) goes to rejected. The for loop makes the rule visible and appends records in their original encounter order.

Each branch calls the built-in list method list.append, which adds one item to the end of the chosen list. No sorting occurs, so records with equal scores preserve their input ordering too. This approach uses long-established standard-library behavior and has no newer API version requirement.

The boundary is intentional: >= 60 includes exactly 60, whereas > 60 would not. A production rule might additionally reject malformed records, missing scores, or non-numeric values before comparing them. This short example assumes consistently shaped, comparable tuples to focus on the partition itself. It also allocates two new lists and retains every record, so it is not a streaming sink for very large sources. The assertions prove the two expected lists for the sample; they do not establish that the threshold is appropriate for another domain.

AI assistance disclosure: this article was drafted with AI assistance and checked against the cited Python documentation.

records = [("ada", 88), ("ben", 57), ("cy", 73)]
accepted = []
rejected = []

for record in records:
    if record[1] >= 60:
        accepted.append(record)
    else:
        rejected.append(record)

assert accepted == [("ada", 88), ("cy", 73)]
assert rejected == [("ben", 57)]
print(accepted)
print(rejected)
[('ada', 88), ('cy', 73)]
[('ben', 57)]

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic