Loading subject…
The two guarantees are a trade: a set gives up ordering and position to buy fast membership testing and automatic removal of duplicates.
| Property | Set | List or array |
|---|---|---|
| Duplicates | Discarded automatically | Kept, and each copy takes its own position |
| Order | Not guaranteed, and may differ between runs | Fixed, and elements are addressed by index |
| Membership test | O(1) on average, one hash and one check | O(n), scan until found |
| Access by position | Not available at all | O(1) in an array |
| Typical use | Tracking which items have been seen | Keeping items in a known sequence |
Both languages ship a set type, so a set is almost never built from scratch and the work is knowing which method performs which operation.
Java
Python
import java.util.HashSet;import java.util.Set;
Set<Integer> a = new HashSet<>(Set.of(1, 2, 3));Set<Integer> b = new HashSet<>(Set.of(3, 4, 5));
// membership, add, removeboolean has2 = a.contains(2); // truea.add(2); // already present, a is unchangeda.remove(1); // a is now {2, 3}
// subset and supersetSet<Integer> small = Set.of(2);boolean smallInsideA = a.containsAll(small); // true, small is a subset of aboolean aInsideSmall = small.containsAll(a); // false, a is not a subset of small
// union, intersection and difference, on copies so a and b surviveSet<Integer> union = new HashSet<>(a);union.addAll(b); // {2, 3, 4, 5}
Set<Integer> intersection = new HashSet<>(a);intersection.retainAll(b); // {3}
Set<Integer> difference = new HashSet<>(a);difference.removeAll(b); // {2}a = {1, 2, 3}b = {3, 4, 5}
# membership, add, removehas_2 = 2 in a # Truea.add(2) # already present, a is unchangeda.remove(1) # a is now {2, 3}a.discard(9) # remove(9) would raise KeyError, discard does not
# subset and supersetsmall = {2}small_inside_a = small.issubset(a) # True, same as small <= aa_inside_small = a.issubset(small) # Falsea_is_superset = a.issuperset(small) # True, same as a >= small
# union, intersection and difference, which return new setsunion = a | b # {2, 3, 4, 5}, same as a.union(b)intersection = a & b # {3}, same as a.intersection(b)difference = a - b # {2}, same as a.difference(b)