Distinct and counted

Lesson 43 of 54 · Python Foundations

Converting a list to a set removes duplicate values; converting back to a list does not restore the original order. Sorting is an option when alphabetical order is useful and the values are mutually comparable.

visits = ["east", "west", "east", "north"]
unique = set(visits)
print(len(visits), len(unique))
print(sorted(unique))
4 3
['east', 'north', 'west']

To preserve the first occurrence order instead, maintain both a set for membership and a list for the result:

visits = ["east", "west", "east", "north"]
seen = set()
ordered = []
for place in visits:
    if place not in seen:
        seen.add(place)
        ordered.append(place)
print(ordered)
['east', 'west', 'north']

A set alone does not count repetitions. Keep a separate counter when both total occurrences and distinct values matter:

readings = ["wet", "dry", "wet", "WET", "wet"]
alerts = {"wet", "WET"}
seen_alerts = set()
alert_count = 0
for reading in readings:
    if reading in alerts:
        alert_count += 1
        seen_alerts.add(reading)
print(alert_count)
print(sorted(seen_alerts))
4
['WET', 'wet']

The counter records four alert occurrences, including repeated wet readings. The set records two distinct alert labels: wet and WET are different strings because comparisons are case-sensitive.