Codectionary / Developer documentation / Python

Sets

A set is an unordered collection of unique, hashable items, created with curly braces or the set() function. Sets automatically eliminate duplicates and support fast membership testing, along with mathematical set operations like union, intersection, and difference. They're especially useful for deduplicating data and for comparing two collections to find overlaps or differences.

Syntax

{item1, item2, item3}

Examples

Creating Sets

Building a set and observing automatic deduplication.

numbers = {1, 2, 2, 3, 3, 3}
print(numbers)  # {1, 2, 3} - duplicates removed automatically

empty = set()  # NOT {} - that creates an empty dict instead
print(type(empty))

Set Operations

Using union, intersection, and difference to compare sets.

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

print(a | b)   # union: {1, 2, 3, 4, 5, 6}
print(a & b)   # intersection: {3, 4}
print(a - b)   # difference: {1, 2}
print(a ^ b)   # symmetric difference: {1, 2, 5, 6}

Adding and Removing Items

Modifying a set after creation.

tags = {"python", "web"}

tags.add("backend")
print(tags)

tags.discard("web")   # no error if 'web' isn't present
print(tags)

print("python" in tags)  # fast membership check

Removing Duplicates from a List

A very common practical use of sets: deduplicating a list while (optionally) preserving order.

names = ["Fola", "Zain", "Fola", "Jamal", "Zain"]

unique_names = list(set(names))
print(unique_names)  # order not guaranteed

# Preserve original order while deduplicating
seen = set()
ordered_unique = []
for name in names:
    if name not in seen:
        seen.add(name)
        ordered_unique.append(name)

print(ordered_unique)  # ['Fola', 'Zain', 'Jamal']

Best practices

  • Use set() to create an empty set - {} creates an empty dictionary instead, a common source of confusion
  • Reach for a set when you need fast membership testing (x in my_set) on a large collection - it is much faster than checking a list
  • Use sets to deduplicate data, but remember they do not preserve insertion order in general (use a dict or an ordered loop if order matters)
  • Only hashable items (numbers, strings, tuples) can go in a set - lists and dictionaries cannot be set members

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation

Lists
A list is Python's built-in ordered, mutable collection type, created with square brackets. Lists can hold items of any type - even a mix of types - and support indexing, slicing, and a wide range of built-in methods for adding, removing, and reordering elements. Because they are mutable, lists can be changed in place after creation, which makes them the go-to structure for collections that grow or shrink over time.
Tuples
A tuple is an ordered, immutable collection, created with parentheses (or often just commas). Once created, a tuple's contents cannot be changed, added to, or removed - this immutability makes tuples faster than lists and safe to use as dictionary keys or in sets. Tuples are commonly used for fixed collections of related values, like coordinates or RGB colors, and for returning multiple values from a function.
Dictionaries
A dictionary stores data as key-value pairs, created with curly braces. Keys must be unique and hashable (strings, numbers, or tuples are common choices), while values can be anything, including other dictionaries or lists. Since Python 3.7, dictionaries maintain insertion order. They are one of the most heavily used data structures in Python, ideal for representing structured records, lookups, and mappings.
List Comprehensions
A list comprehension is a concise, expressive way to build a new list by applying an expression to every item in an iterable, optionally filtering with a condition. It replaces the common pattern of creating an empty list and appending to it inside a for loop, condensing that logic into a single readable line. Comprehensions are considered idiomatic Python for simple to moderately complex transformations.