Python Sets Tutorial: 4 Essential Operations for Unique Data

Table of Contents

A set in Python is an unordered collection of unique elements. 

Think of it like a box where you can throw in items but if you try to add the same item twice,  Python will ignore the duplicate.

Today we’ll uncover creative ways to use Python sets and make our code cleaner, faster and smarter.

Let’s take a look at an example below.

				
					fruits = {"apple", "banana", "cherry", "apple"}
print(fruits)

#          {'banana', 'apple', 'cherry'}

				
			

Notice how “apple” appears only once now as the duplicate has been removed.

Why Use Sets?

Sets are great when you need to:

  • Remove duplicates from a list
  • Check membership quickly (in operator is super fast for sets)
  • Perform mathematical operations(like union, intersection, difference)
  • Store unique items only

Let’s explore these in action

Creating a Set

A set can be created in two ways:

  • Using Curly Braces
  • Using set Constructor ([ ])
				
					# curly braces
my_set = {1, 2, 3}

#  set() constructor
another_set = set([1, 2, 3, 3, 4])
print(another_set) 

# Output: {1, 2, 3, 4}

				
			

Retrieving elements from a set:

Elements can be retrieved by using the following methods.

1. Membership Check (in Operator)

  • Definition: Used to quickly verify if a specific element exists within the set, returning either True or False
  • Formula: value in my_set

 

2. Looping (for loop)

  • Definition:Used to process every element in the set one by one, although the elements will be accessed in an arbitrary (unordered) sequence.
  • Formula: for item in my_set: 

 

3. Conversion (list() constructor)

  • Definition: Used to access elements by index. It first converts the set into an ordered data type (like a list), allowing access using standard indexing (my_list[0]).
  • Formula: list(my_set)[index]

 

The following program demonstrates all the methods for retrieving the elements.

				
					tech_set = {"Python", "Java", "C++", "C#"}
print(f"Set: {tech_set}")

# 1. Membership Check 
language = "Java"
is_present = language in tech_set
print(f"1. Is '{language}' in set? {is_present}")

# 2. Looping
print("\n2. Looping through the set:")
for lang in tech_set:
    print(f"- {lang}")

# 3. Conversion
ordered_list = list(tech_set)
first_element_by_index = ordered_list[0]
print(f"3.   Converted List: {ordered_list}")
print(f"   Element at Index 0: {first_element_by_index}")

# output

#       Set: {'C++', 'C#', 'Java', 'Python'}
#          1. Is 'Java' in set? True

#          2. Looping through the set:
#             - C++
#             - C#
#             - Java
#             - Python
#           3.   Converted List: ['C++', 'C#', 'Java', 'Python']
#                Element at Index 0: C++
				
			

 Basic Set Operations

1. Add Elements: Used to add new elements to a set. There are different methods

  • add(): New elements can be added to the set.

          Syntax: set_name.add()

  •  Update function: It is used to add multiple elements(from another set, tuple, or list) to an existing set.

          Syntax: set.update(iterable)

2. Remove Elements: Any elements can be removed from the set. There are four different methods.

  • remove():  removes a specific element (throws an error if that element is not found)

         Syntax: set.remove(element)

  • discard(): removes a specific element (does NOT throw error if not found)

          Syntax: set.discard(element)

  •  pop(): It removes a random element from the set

          Syntax: set.pop()

  • clear():  It erases all the elements from the set.

          Syntax: Set.clear()

 

 Consider the example below. The program below demonstrates ways to add an element and update it by using another array and a list. It can also be used with a tuple and any other iterable.

				
					numbers = {1, 2, 3}
numbers.add(4)
print(numbers)  # : {1, 2, 3, 4}

# Using update() 
numbers.update({5, 6, 7})
print(numbers)  # : {1, 2, 3, 4, 5, 6, 7}

# using update() with list
numbers.update([8, 9, 10])
print(numbers)  # : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
				
			
				
					fruits = {"apple", "mango", "cherry", "banana", "grapes", "pineapple", "blackberry", "jackfruit"}
print(fruits)

# 1. remove()
fruits.remove("banana")
print(fruits)

# 2. discard()
fruits.discard("apple")
print(fruits)

# 3. pop() 
removed_item = fruits.pop()
print(f"After pop(): {fruits}")
print(f"Removed item: {removed_item}")

# 4. clear()
fruits.clear()
print("After clear():", fruits)

#  output


# 1.  {'jackfruit', 'mango', 'blackberry', 'grapes', 'cherry', 'apple', 'pineapple'}
# 2.  {'jackfruit', 'mango', 'blackberry', 'grapes', 'cherry', 'pineapple'}

# 3.  After pop(): {'mango', 'blackberry', 'grapes', 'cherry', 'pineapple'}
#    Removed item: jackfruit
# 4   After clear(): set()
				
			

Mathematical Set Operations

Sets make operations like union, intersection and difference effortless.

1.Union: Definition: Union combines all unique elements that are present in either the first set or the second set (or both). It is denoted by ( | ) operator.

2. Set Intersection: Intersection finds only the elements that are common to both the first set and the second set. It is denoted by ( & ) operator.

3. Set Difference:  Difference finds the elements that are present in the first set but are not present in the second set. It is denoted by ( – ) operator.

4. Symmetric Difference: It combines all unique elements that are in either the first set or the second set, but NOT in both (it excludes the intersection). It is denoted by ( ^ ) operator.

Consider the image representation below.

Visual guide comparing Python set operations: Union, Intersection, Difference, and Symmetric Difference.
A comparative visualization of the four essential set operations in Python sets.
				
					A = {1, 2, 3}
B = {3, 4, 5}

# Union: {1, 2, 3, 4, 5}
print(A | B)

# Intersection: {3}
print(A & B)

# Difference (A - B): {1, 2}
print(A - B)

# Symmetric Difference: {1, 2, 4, 5}
print(A ^ B)
				
			
				
					languages_a = {"Python", "Java", "C++", "JavaScript"}
languages_b = {"C++", "Python", "HTML", "CSS"}

print(f"Set A (Know): {languages_a}")
print(f"Set B (To Learn): {languages_b}")

# 1. UNION (|)
union_set = languages_a | languages_b
print(f"1.  {union_set}")

# 2. INTERSECTION (&)
intersection_set = languages_a & languages_b
print(f"2. {intersection_set}")

# 3. DIFFERENCE (-)  Finds languages in A but NOT in B
difference_set = languages_a - languages_b
print(f"3. {difference_set}")

# 4. SYMMETRIC DIFFERENCE (^)
# Finds languages unique to either set 
sym_difference_set = languages_a ^ languages_b
print(f"4. {sym_difference_set}")
				
			

Frozenset

A frozenset is just like a normal set but it is immutable means you can’t add, remove or modify the elements once it is created.  A frozenset keyword is used to create a frozenset.

Why use a frozenset

  • You need a set that should not change.

  • You want to use a set as a key in a dictionary or inside another set (since normal sets can’t be nested because they’re mutable).

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


print("Length:", len(numbers))
print("Is 3 in frozenset?", 3 in numbers)

# output

#       frozenset({1, 2, 3, 4})
#       Length: 4
#       Is 3 in  frozenset? True


				
			

Some Practice Questions

1. Write a Python program to remove duplicates from a list using a set.

2. Write a Python program to print the largest and smallest element in the set without built in function.

3. Write a program to find the missing numbers and duplicate numbers in a set. Consider the set [1, 2, 3, 4, 4, 6, 7, 7, 9, 10]

				
					# 1

numbers = {25, 10, 45, 30, 5}

print("Set:", numbers)
print("Largest number:", max(numbers))
print("Smallest number:", min(numbers))


# 2

fruits = ["apple", "mango", "apple", "cherry", "mango"]
unique_fruits = set(fruits)

print("Original List:", fruits)
print("Unique Fruits:", unique_fruits)

# 3

numbers = [1, 2, 3, 4, 4, 6, 7, 7, 9, 10]

unique_numbers = set(numbers)
duplicates = [num for num in numbers if numbers.count(num) > 1]
duplicates = set(duplicates)

all_numbers = set(range(1, 11))
missing_numbers = all_numbers - unique_numbers

print("Original List:", numbers)
print("Unique Numbers:", unique_numbers)
print("Duplicate Numbers:", duplicates)
print("Missing Numbers:", missing_numbers)


				
			

FAQ (Frequently Asked  Questions)

1. How to add a set in Python?

Use the add method()

my_set = {1, 2, 3}
my_set.add(4)

 

2. How to declare an empty set?

We can create an empty set by using set() constructor

empty_set = set()

 

3. How to convert a list to a set in Python?

We can convert list to a set by using the set() function.

my_list = [1, 2, 2, 3]
my_set = set(my_list)

 

4. What is the difference between set and frozenset in Python?

Featuressetfrozenset
MutableYesNo
HashableNoYes
Can be a dict keyNoYes
Supports add/removeYesNo

5. Is a set ordered in Python?

No sets are unordered the elements have no fixed position or index.

 

6.What is a set union in Python?

  • A union merges all unique members of two or more sets.

 
a = {1, 2}
b = {2, 3}
print(a | b) # Output: {1, 2, 3}
 

7. Is a set mutable in Python?

Yes  sets are mutable, meaning you can modify them using methods like add() or remove().

Leave a Reply

Your email address will not be published. Required fields are marked *