Filter repeated values while retaining first order
Filter repeated values while retaining first order
A set is useful for remembering whether a value has appeared, but sets do not express the order needed for a first-seen report. first_values combines a seen set with an output list. For every input value, it appends to the list only when the value is absent from seen, then records that value in the set.
Given the event labels in the example, the second "open" and second "closed" do not reach output. The result is ["open", "queued", "closed"], in the same order as their first appearances. The assertion confirms both the duplicate filtering and the order for this concrete list.
Membership testing in a set is typically efficient, but this technique requires hashable values. Lists and dictionaries cannot be added to seen and will raise TypeError; use a hashable key derived from such records instead. Equality also matters: values considered equal by Python, such as 1 and True, are treated as repeats. This function retains values in memory in both seen and output, so it is not suitable for an unbounded stream when every historic value must remain distinguishable.
AI assistance was used to draft this article.
def first_values(values):
seen = set()
output = []
for value in values:
if value not in seen:
seen.add(value)
output.append(value)
return output
labels = ["open", "queued", "open", "closed", "queued", "closed"]
unique_labels = first_values(labels)
assert unique_labels == ["open", "queued", "closed"]
print("first values:", unique_labels)
Expected stdout:
first values: ['open', 'queued', 'closed']
Source: Python documentation: set types
Comments
Post a Comment