Content · Programming · Python

Python Sets: Creating Unordered Unique Collections

A set stores distinct hashable values and supports fast average membership tests. It does not promise a stable iteration order and cannot be accessed by numeric index. See two practical examples, edge cases and common.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

A visitor counter wants unique cities rather than every repeated observation.

What You Need to Understand


A set stores distinct hashable values and supports fast average membership tests. It does not promise a stable iteration order and cannot be accessed by numeric index.

When to Use It


A visitor counter wants unique cities rather than every repeated observation.

Step-by-Step Python Example


cities = {"Haifa", "Tel Aviv", "Haifa"}
cities.add("Eilat")
print(len(cities))
print("Eilat" in cities)

How the Example Works


Repeated city names collapse to one set element, so the size reflects unique cities.

Example Output


3
True
2

A Second Example


Compare this smaller variation with the main example, then experiment with your own values.

codes = ["P1", "P2", "P1"]
print(len(set(codes)))

Important Behavior and Edge Cases


Never depend on the printed ordering of a set. Values must be hashable; a plain list cannot be inserted as one set member.

Try It Yourself


Make a set from a list of product codes and count unique codes.

Common Beginner Mistakes


  • Never depend on the printed ordering of a set. Values must be hashable; a plain list cannot be inserted as one set member.
  • Depending on set iteration order or using a set when duplicates and original positions must be preserved.

Key Takeaways


  • A set stores distinct hashable values and supports fast average membership tests.
  • Repeated city names collapse to one set element, so the size reflects unique cities.
  • Never depend on the printed ordering of a set.
Share this resourceSend this page to someone who may find it useful.