Python

Python Sets

A set is a Python data type used to store a collection of unique elements.

The two most important characteristics of a set are:

A set does not allow duplicate values, and it does not maintain elements by index.

For example:

numbers = {10, 20, 30, 20, 40, 10}

print(numbers)

Duplicate values are automatically removed.

The result will contain only unique values:

{10, 20, 30, 40}

Sets are especially useful when you need to:

  • Remove duplicate data.
  • Check whether an item exists.
  • Compare two collections.
  • Find common elements.
  • Find elements that exist in one collection but not another.
  • Perform mathematical set operations.

1. Creating a Set

A set is usually created using curly braces {}.

Example

x = {1, 20, 100, 200, 400, 150, 50, 10}

print(x)

The order in which elements appear when printed should not be relied upon.

A set is not accessed by position like a list or tuple.

2. Sets Automatically Remove Duplicates

One of the most useful features of a set is that it stores only unique values.

Example

x = {1, 20, 100, 200, 400, 150, 50, 10, 200}

print(x)

Notice that 200 appears twice in the source code.

The set keeps only one copy.

Conceptually:

Original:
1, 20, 100, 200, 400, 150, 50, 10, 200

Unique values:
1, 20, 100, 200, 400, 150, 50, 10

3. Important Characteristics of Sets

Python sets have the following characteristics:

  • Sets contain unique elements.
  • Sets are unordered.
  • Sets are mutable.
  • Sets do not support normal indexing.
  • Sets do not support normal slicing.
  • Sets can contain different hashable data types.
  • Sets can be modified after creation.
  • Sets support mathematical operations such as union and intersection.
  • A set can contain immutable elements such as numbers, strings, and tuples.
  • A set cannot directly contain mutable objects such as lists or dictionaries.

4. Finding the Length of a Set

Use len() to find the number of unique elements.

Example

x = {1, 20, 100, 200, 400, 150, 50, 10, 200}

print(len(x))

Output

8

Even though 200 was written twice, the set contains it only once.

Therefore, the length is 8.

5. Checking the Data Type

Use type() to check the type of a variable.

x = {1, 2, 3, 4}

print(type(x))

Output

<class 'set'>

6. Creating a Set Using set()

Python provides the set() constructor.

Example

y = set(("a", "b", "c", "d"))

print(y)

Output

The output contains:

{'a', 'b', 'c', 'd'}

The exact display order should not be relied upon.

7. Empty Set

There is an important difference between {} and set().

{} creates an empty dictionary

x = {}

print(type(x))

Output:

<class 'dict'>

set() creates an empty set

x = set()

print(type(x))

Output:

<class 'set'>

Important Rule

{}       → Empty dictionary
set()    → Empty set

This is an important point to remember.

8. Adding an Element Using add()

The add() method adds one element to a set.

Example

y = {"a", "b", "c", "d"}

y.add("z")

print(y)

The set now contains "z".

Adding an Existing Element

If you try to add an element that already exists, nothing happens.

x = {1, 2, 3}

x.add(2)

print(x)

The result still contains only:

{1, 2, 3}

This is because sets only store unique values.

9. Adding Multiple Elements Using update()

The update() method can add multiple elements from another iterable.

Example

x = {1, 2, 3}
y = {4, 5, 6}

x.update(y)

print(x)

Conceptually, the result contains:

{1, 2, 3, 4, 5, 6}

10. add() vs update()

This distinction is important.

add()

Adds one element.

x = {1, 2, 3}

x.add(4)

Result:

{1, 2, 3, 4}

update()

Adds elements from another iterable.

x = {1, 2, 3}

x.update([4, 5, 6])

Result:

{1, 2, 3, 4, 5, 6}

You can use:

x.update("abc")

and the characters are added as individual elements.

11. Checking Whether an Element Exists

Use the in operator to check whether an element is present.

Example

numbers = {10, 20, 30, 40}

print(20 in numbers)
print(50 in numbers)

Output

True
False

You can also use not in.

print(50 not in numbers)

Output:

True

This is one of the most practical uses of sets.

12. Why Sets Do Not Use Indexes

Lists and tuples have indexes:

fruits = ["apple", "mango", "papaya"]

print(fruits[0])

But sets do not support this type of access:

fruits = {"apple", "mango", "papaya"}

print(fruits[0])

This produces an error because sets are not index-based collections.

Instead, use membership checking:

print("apple" in fruits)

13. Removing an Element Using remove()

The remove() method removes a specified element.

Example

fruits = {"apple", "mango", "papaya", "cherry"}

fruits.remove("mango")

print(fruits)

"mango" is removed from the set.

Important

If the element does not exist, remove() raises a KeyError.

fruits.remove("banana")

This produces an error because "banana" does not exist in the set.

14. Removing an Element Using discard()

discard() also removes an element.

The important difference is:

discard() does not produce an error if the element does not exist.

Example

fruits = {"apple", "mango", "papaya"}

fruits.discard("mango")

print(fruits)

Trying to Remove a Missing Element

fruits.discard("banana")

print(fruits)

No error occurs.

remove() vs discard()

MethodElement existsElement doesn't exist
remove()Removes itRaises KeyError
discard()Removes itDoes nothing

When you are unsure whether an element exists, discard() is often more convenient.

15. Removing an Arbitrary Element Using pop()

The pop() method removes and returns an arbitrary element from a set.

Example

numbers = {10, 20, 30, 40}

item = numbers.pop()

print("Removed:", item)
print("Remaining:", numbers)

Because sets are unordered, you should not assume which element will be removed.

This is different from:

list.pop()

For a list, pop() normally removes the last element unless an index is specified.

For a set, pop() removes an arbitrary element.

16. Clearing a Set

The clear() method removes all elements from a set.

Example

y = {"a", "b", "c", "d"}

y.clear()

print(y)

Output

set()

The set still exists, but it is empty.

17. Deleting a Set Using del

The del statement can delete the entire set.

Example

a = {1, 2, 3}

del a

After this statement, the variable a no longer exists.

Therefore:

print(a)

would produce a NameError.

18. clear() vs del

OperationResult
x.clear()Removes all elements, set remains
del xDeletes the set variable completely

19. Union of Sets

The union of two sets contains all unique elements from both sets.

Suppose:

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}

The union is:

{1, 2, 3, 4, 5, 6}

Using union()

test = x.union(y)

print(test)

20. Union Using |

Python also provides the | operator for union.

test = x | y

print(test)

Both approaches produce the same set.

Concept

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}

Union:
{1, 2, 3, 4, 5, 6}

21. Intersection of Sets

The intersection contains only the elements that exist in both sets.

Example

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}

test = x.intersection(y)

print(test)

Result

{3, 4}

The common elements are 3 and 4.

22. Intersection Using &

You can also use the & operator.

test = x & y

print(test)

This is equivalent to:

x.intersection(y)

23. Difference Between Sets

The difference operation finds elements that exist in the first set but not in the second set.

Example

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}

test = x.difference(y)

print(test)

Output

{1, 2}

1 and 2 exist in x, but not in y.

24. Difference Is Directional

This is very important.

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}

print(x.difference(y))
print(y.difference(x))

Conceptually:

x - y → {1, 2}

y - x → {5, 6}

The order matters.

25. Difference Using -

You can also use the - operator.

print(x - y)
print(y - x)

This is equivalent to difference().

26. Symmetric Difference

The symmetric difference returns elements that exist in either set, but not in both.

Example

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}

test = x.symmetric_difference(y)

print(test)

Result

{1, 2, 5, 6}

The common values 3 and 4 are removed.

27. Symmetric Difference Using ^

You can also use the ^ operator.

test = x ^ y

print(test)

This produces the same result as:

x.symmetric_difference(y)

28. Set Operations Summary

Suppose:

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}
OperationMethodOperatorResult
Unionx.union(y)x | y{1,2,3,4,5,6}
Intersectionx.intersection(y)x & y{3,4}
Differencex.difference(y)x - y{1,2}
Symmetric Differencex.symmetric_difference(y)x ^ y{1,2,5,6}

29. Updating a Set Using Union

update() modifies the original set by adding elements from another iterable.

Example

x = {1, 2, 3}
y = {3, 4, 5}

x.update(y)

print(x)

The resulting set contains:

{1, 2, 3, 4, 5}

Unlike union(), update() changes the original set.

Compare

x = {1, 2, 3}
y = {3, 4, 5}

z = x.union(y)

print(x)
print(z)

x remains unchanged.

But:

x.update(y)

changes x.

30. Updating an Intersection Using intersection_update()

The intersection_update() method keeps only the elements that exist in both sets.

Example

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}

x.intersection_update(y)

print(x)

Result

{3, 4}

Unlike intersection(), this changes the original set.

31. Updating a Difference Using difference_update()

The difference_update() method removes elements from the first set that also exist in another set.

Example

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}

x.difference_update(y)

print(x)

Result

{1, 2}

32. Updating Symmetric Difference

The symmetric_difference_update() method changes the original set so that it contains elements that are in either set, but not in both.

Example

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}

x.symmetric_difference_update(y)

print(x)

Result

{1, 2, 5, 6}

33. Subset

A set is a subset of another set if every element of the first set is also present in the second set.

Example

x = {1, 2, 3}
y = {1, 2, 3, 4, 5}

print(x.issubset(y))

Output

True

Because every element of x exists in y.

34. Subset Using <=

You can also write:

print(x <= y)

This checks whether x is a subset of y.

35. Superset

A set is a superset when it contains all the elements of another set.

Example

x = {1, 2, 3}
y = {1, 2, 3, 4, 5}

print(y.issuperset(x))

Output

True

Because y contains every element of x.

36. Superset Using >=

You can also write:

print(y >= x)

This checks whether y is a superset of x.

37. Checking Whether Two Sets Are Disjoint

Two sets are disjoint when they have no common elements.

Example

x = {1, 2, 3}
y = {4, 5, 6}

print(x.isdisjoint(y))

Output

True

There are no common elements.

If they have a common element:

x = {1, 2, 3}
y = {3, 4, 5}

print(x.isdisjoint(y))

Output:

False

38. Frozen Sets

Python also provides a special type called frozenset.

A frozenset is an immutable set.

Example

numbers = frozenset([1, 2, 3, 4])

print(numbers)
print(type(numbers))

Output

frozenset({1, 2, 3, 4})
<class 'frozenset'>

Unlike a normal set, a frozenset cannot be modified.

For example:

numbers.add(5)

will produce an error because a frozenset cannot be changed.

39. Set and Frozenset

FeatureSetFrozenset
MutableYesNo
Unique elementsYesYes
OrderedNoNo
add()YesNo
remove()YesNo
Set operationsYesYes
Can be used as a dictionary keyNoYes

40. Removing Duplicates from a List

One of the most practical uses of a set is removing duplicate values from a list.

Example

numbers = [10, 20, 10, 30, 20, 40, 30, 50]

unique_numbers = set(numbers)

print(unique_numbers)

The resulting set contains only unique values.

Converting Back to a List

unique_numbers = list(set(numbers))

print(unique_numbers)

This gives us a list containing unique values.

Important

Because sets are unordered, converting a list to a set and back can change the original ordering.

41. Preserving Order While Removing Duplicates

If you want to remove duplicates while preserving the original order, a useful approach is:

numbers = [10, 20, 10, 30, 20, 40, 30, 50]

unique_numbers = list(dict.fromkeys(numbers))

print(unique_numbers)

Output

[10, 20, 30, 40, 50]

This is useful in real applications when duplicate values need to be removed without losing their original sequence.

42. Set Comprehension

Python also supports set comprehension, which provides a concise way to create sets.

Example

numbers = {x * 2 for x in range(1, 6)}

print(numbers)

Conceptually, the values are:

{2, 4, 6, 8, 10}

Another example:

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = {x for x in numbers if x % 2 == 0}

print(even_numbers)

Result:

{2, 4, 6}

43. Sets Cannot Contain Mutable Elements

A set requires its elements to be hashable.

Therefore, you cannot directly put a list inside a set.

Invalid Example

x = {[1, 2], [3, 4]}

This produces:

TypeError: unhashable type: 'list'

However, tuples can be elements of a set if their contents are hashable.

Valid Example

x = {(1, 2), (3, 4)}

print(x)

44. Practical Example - Common Students

Suppose one class has Python students and another class has Django students.

python_students = {"Ram", "John", "Sita", "Michael"}
django_students = {"John", "Sita", "David", "Alex"}

Students in Both Courses

print(python_students.intersection(django_students))

Result:

{'John', 'Sita'}

Students Only in Python

print(python_students.difference(django_students))

Students Enrolled in Either Course

print(python_students.union(django_students))

Students Taking Only One of the Two Courses

print(python_students.symmetric_difference(django_students))

This demonstrates why sets are useful beyond simply removing duplicates.

45. Set Methods Summary

MethodPurpose
add()Adds one element
update()Adds multiple elements
remove()Removes a specified element; raises an error if missing
discard()Removes a specified element without error if missing
pop()Removes an arbitrary element
clear()Removes all elements
union()Combines unique elements from sets
intersection()Finds common elements
difference()Finds elements only in the first set
symmetric_difference()Finds elements present in either set but not both
intersection_update()Updates set with common elements
difference_update()Removes common elements
symmetric_difference_update()Updates set with non-common elements
issubset()Checks whether a set is a subset
issuperset()Checks whether a set is a superset
isdisjoint()Checks whether sets have no common elements
copy()Creates a shallow copy

46. Set Operators Summary

Suppose:

x = {1, 2, 3, 4}
y = {3, 4, 5, 6}
OperationOperatorResult
Unionx | y{1,2,3,4,5,6}
Intersectionx & y{3,4}
Differencex - y{1,2}
Reverse Differencey - x{5,6}
Symmetric Differencex ^ y{1,2,5,6}

47. Complete Copy Code

# ==========================================
# Python Sets
# ==========================================


# Creating a set
x = {1, 20, 100, 200, 400, 150, 50, 10, 200}

print(x)


# Length
print(len(x))


# Type
print(type(x))


# Creating a set using set()
y = set(("a", "b", "c", "d"))

print(y)


# add()
y.add("z")

print(y)


# Adding an existing value
y.add("z")

print(y)


# update()
x.update(y)

print(x)


# discard()
y.discard("b")

print(y)


# pop()
removed = y.pop()

print("Removed:", removed)
print("Remaining:", y)


# clear()
y.clear()

print(y)


# del
a = {1, 2, 3}

del a


# Set operations
x = {1, 2, 3, 4, 5, 6}
y = {5, 6, 7, 3, 8, 9, 10}


# Difference
test = x.difference(y)

print("Difference:", test)


# Intersection
test = x.intersection(y)

print("Intersection:", test)


# Union
test = x.union(y)

print("Union:", test)


# Symmetric difference
test = x.symmetric_difference(y)

print("Symmetric Difference:", test)


# Membership
print(5 in x)
print(100 in x)


# Subset
a = {1, 2}
b = {1, 2, 3, 4}

print(a.issubset(b))


# Superset
print(b.issuperset(a))


# Disjoint
c = {10, 20}

print(a.isdisjoint(c))

 

48. Practice Exercise

Create two sets:

web_students = {"Ram", "John", "Sita", "Michael"}
data_students = {"Sita", "Michael", "David", "Alex"}

Perform the following operations:

  1. Print both sets.
  2. Find the total number of students in each set.
  3. Find students enrolled in both courses.
  4. Find students enrolled only in the web course.
  5. Find students enrolled only in the data course.
  6. Find all unique students.
  7. Find students enrolled in exactly one course.
  8. Check whether "Ram" is in the web course.
  9. Add a new student.
  10. Safely remove a student using discard().
  11. Check whether both sets are disjoint.
  12. Check whether one set is a subset of another.

49. Challenge Exercise - Duplicate Data

Consider the following list:

emails = [
    "john@example.com",
    "ram@example.com",
    "john@example.com",
    "sita@example.com",
    "ram@example.com",
    "alex@example.com"
]

Perform the following:

  1. Find how many total email entries exist.
  2. Convert the list into a set.
  3. Find how many unique emails exist.
  4. Convert the unique emails back into a list.
  5. Check whether "john@example.com" exists.
  6. Add "michael@example.com".
  7. Remove "alex@example.com".
  8. Create another set of emails and find common emails between the two sets.

50. Real-World Uses of Sets

Sets are particularly useful in real-world programming for:

Removing duplicates

unique_users = set(user_list)

Checking membership

if user_id in active_users:
    print("User is active")

Comparing permissions

required_permissions = {"read", "write"}
user_permissions = {"read", "write", "delete"}

print(required_permissions.issubset(user_permissions))

Finding common data

common_skills = python_skills.intersection(django_skills)

Comparing two groups

difference = group_a.symmetric_difference(group_b)

Sets are therefore useful in web applications, data analysis, authentication systems, recommendation systems, APIs, and database-related programming.

51. List vs Tuple vs Set vs Dictionary

By this point, it is useful to compare the four major Python collection types.

FeatureListTupleSetDictionary
Syntax[](){}{key: value}
OrderedYesYesNoYes
MutableYesNoYesYes
DuplicatesYesYesNoKeys: No
IndexingYesYesNoBy key
SlicingYesYesNoNo
Key-value pairsNoNoNoYes
Main purposeCollectionFixed collectionUnique valuesRelated named data
Interactive Sandbox
Python