SyntaxStudy
Sign Up
Python Beginner 7 min read

Set Basics

Set Basics

Sets are unordered collections of unique elements. They are mutable, but every element must be hashable (immutable).

Creating Sets

s1 = {1, 2, 3, 4}
s2 = set([1, 2, 2, 3, 3, 4])  # duplicates removed
print(s2)   # {1, 2, 3, 4}

empty_set = set()   # NOT {} — that creates a dict!

add() & discard() / remove()

fruits = {"apple", "banana", "cherry"}
fruits.add("mango")
fruits.add("apple")    # no duplicate added
print(fruits)

fruits.discard("banana")  # no error if missing
fruits.remove("cherry")   # raises KeyError if missing
fruits.discard("kiwi")    # safe — does nothing

Membership Testing

# Sets use O(1) hash lookup — much faster than lists
print("mango" in fruits)   # True
print("grape" not in fruits)  # True

Iterating

for fruit in sorted(fruits):
    print(fruit)
Example
nums = {3, 1, 4, 1, 5, 9, 2, 6, 5}
print(nums)        # unique values, unordered
print(len(nums))   # 7

nums.add(10)
nums.discard(1)
print(42 in nums)  # False
print(9 in nums)   # True
Pro Tip

Sets are great for deduplicating a list: unique = list(set(my_list)). Be aware that order is not preserved.