Use a set to detect duplicate identifiers

Type one expression at a time and check its delimiters. · 137 words

A set keeps each item only once, so it can reveal repeated identifiers in experimental records. A duplicate image ID may hide a data leak or overwrite a record. Compare the list length with the set length: identifiers = ['img_001', 'img_002', 'img_001', 'img_003'] unique_ids = set(identifiers) print(len(identifiers), len(unique_ids)) The output is 4 3, so one identifier repeats. Sorting the set is optional and is only useful for stable display.

Check duplicates before a pipeline starts. This helper returns True only for a new identifier: def register_identifier(seen, new_id): if new_id in seen: return False seen.add(new_id) return True seen = {'img_001'} print(register_identifier(seen, 'img_001')) # False print(register_identifier(seen, 'img_004')) # True print(sorted(seen)) The first call changes nothing. The second adds img_004. The final sorted list is ['img_001', 'img_004']. This test finds exact matches only, not near-duplicates such as img_01 and img_001.

Check your recall

In the first example, how do you know that one identifier is duplicated?

Check your answer

The original list has 4 items, but its set has only 3 unique identifiers. The repeated value is img_001.

Sources and credits

Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.