PROGRAMMING-CONCEPTS

Set: Definition, Purpose, and Examples

A set is a collection of unique, unordered values. Unlike arrays or lists, a set automatically removes duplicates and focuses on membership — whether a value is present. Sets are ideal when you need fast lookups, distinct data, or mathematical set operations like unions and intersections.

Sets appear across Python, JavaScript, TypeScript, and Swift. Even though syntax differs, the behavior is consistent: store unique values and retrieve them quickly.


Why Sets Matter

Sets solve problems where order isn’t important but uniqueness is. Developers use them when they care about:

  • Removing duplicates
  • Checking membership efficiently
  • Combining or comparing groups of values
  • Representing categories, tags, or relationships
  • Ensuring data integrity in collections

A set answers questions like:

“Does this item exist?”

“How many distinct values are there?”

without the overhead of searching through lists.


Sets in Python

Python’s set type is one of the most flexible implementations.

Creating a set

colors = {"red", "blue", "green"}

Python automatically removes duplicates if they appear.

Adding and removing values:

colors.add("yellow")
colors.discard("blue")

These operations run quickly because sets use hash-based storage.

Checking membership:

"red" in colors

This is one of the most readable membership checks in any language.

Python’s set operations

a = {1, 2, 3}
b = {3, 4, 5}

a.union(b)
a.intersection(b)
a.difference(b)

Python’s implementation directly mirrors mathematical set theory, making it especially clear for data analysis, machine learning, and text processing.


Sets in JavaScript

JavaScript includes a built-in Set object.

Creating a set

const items = new Set(["apple", "banana", "apple"]);

Even though “apple” appears twice, the set stores only one instance.

Adding and deleting:

items.add("kiwi");
items.delete("banana");

Checking membership:

items.has("apple");

JavaScript’s Set is useful when eliminating duplicates from arrays:

const unique = [...new Set([1, 2, 2, 3, 3, 4])];

This is one of the most common real-world uses.


Sets in TypeScript

TypeScript uses JavaScript’s Set but adds type safety.

const ids: Set<number> = new Set();
ids.add(100);
ids.add(200);

TypeScript makes it easier to keep set contents consistent, especially when storing complex objects or identifiers in web apps.


Sets in Swift

Swift includes a native Set type similar to Python’s.

var names: Set<String> = ["Anna", "Bob", "Anna"]

Swift automatically ensures uniqueness.

Core operations:

names.insert("Chris")
names.contains("Anna")
names.remove("Bob")

Swift’s sets are strongly typed, improving safety in iOS and macOS development when grouping identifiers or states.


When to Use a Set

1. When you need unique values

This is the most direct use case.

Python:

unique_tags = set(tags_list)

JavaScript:

const uniqueTags = new Set(tagsArray);

This removes duplicates instantly.

2. When fast membership checks matter

Sets answer “Is this value present?” far faster than lists or arrays.

This is helpful when validating input, filtering banned items, or matching categories.

3. When performing set operations

Union, intersection, and difference provide powerful data comparison tools.

For example, determining shared interests between users.

4. When representing groups without order

If order doesn’t matter, sets are cleaner and safer than lists.


Real-World Example: User Permissions

Permissions are naturally modeled as sets.

Python

user_permissions = {"read", "write"}
required = {"read"}

if required.issubset(user_permissions):
    print("Allowed")

This avoids fragile boolean logic and supports clean comparisons.

JavaScript

const user = new Set(["view", "edit"]);
user.has("edit");

This structure aligns perfectly with role-based access control.


Real-World Example: Eliminating Duplicate API Results

APIs frequently return repeated values.

JavaScript:

const ids = data.map(item => item.id);
const distinct = [...new Set(ids)];

This extracts unique identifiers with a single expression.


Real-World Example: Tracking visited items

A set is ideal for tracking which items you’ve already processed.

Python:

visited = set()

for page in pages_to_crawl:
    if page not in visited:
        visited.add(page)
        crawl(page)

This pattern appears in crawlers, graph algorithms, and recommendation systems.


Set Operations Across Languages

Even though syntax varies, most languages support the same conceptual operations.

Python

a | b      # union
a & b      # intersection
a - b      # difference

JavaScript (manual approach)

Because JavaScript doesn’t include built-in operators, developers often create functions:

function union(a, b) {
  return new Set([...a, ...b]);
}

Swift

a.union(b)
a.intersection(b)
a.subtracting(b)

The idea remains consistent: combine groups, find overlap, and compare differences.


Sets in React Applications

React components often manage collections such as selected items or tags. A set prevents duplicates in state.

const [selected, setSelected] = useState(new Set());

function toggle(id) {
  const next = new Set(selected);
  next.has(id) ? next.delete(id) : next.add(id);
  setSelected(next);
}

This pattern keeps selection logic predictable and avoids repetition.


Common Mistakes

  • Expecting sets to preserve order — they don’t
  • Treating sets like arrays and trying to access items by index
  • Forgetting that JavaScript’s Set equality is reference-based, not value-based
  • Mixing complex objects without providing a stable comparison method
  • Using arrays when data must be unique

Recognizing when an unordered, duplicate-free structure is appropriate prevents subtle bugs.


Best Practices

  • Use sets for membership questions, not arrays
  • Convert arrays to sets when cleaning data
  • Prefer set operations for comparing groups
  • When ordering matters, convert the set back to an array intentionally
  • Keep set contents simple (strings, numbers, IDs) unless uniqueness rules are well-defined

Clear distinctions between sets and lists make your code more predictable.


Summary

A set is a collection that stores unique, unordered values and offers fast membership checks. Python, JavaScript, TypeScript, and Swift all include set implementations that help eliminate duplicates, compare groups, and represent categories or permissions. Sets excel when you care about whether something exists, not where it appears. Understanding when to choose a set over a list or array leads to cleaner, more efficient code across all modern applications.

Learn to Code for Free
Start learning now
button icon
To advance beyond this tutorial and learn to code by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

Reach your coding goals faster