Python Sets


In Python, sets are a built-in data structure used to store unique and unordered elements. Unlike lists or tuples, sets automatically remove duplicate items and do not maintain any particular order. Sets are highly efficient for membership testing, removing duplicates, and performing mathematical operations like union, intersection, and difference.

This tutorial will cover the fundamentals of Python sets, including creation, adding and removing elements, set operations, built-in methods, and practical examples.

What is a Set in Python?

A set is an unordered collection of unique elements enclosed in curly braces {} or created using the set() function. Sets do not allow duplicates and are mutable, meaning you can add or remove elements after creation.

Example:

fruits = {"Apple", "Banana", "Cherry"}
numbers = {1, 2, 3, 4}
mixed_set = {1, "Apple", 3.5, True}

In these examples:

  • fruits contains strings.

  • numbers contains integers.

  • mixed_set contains different data types.

  • Duplicates, if added, are automatically removed.

Creating Sets in Python

You can create sets in multiple ways:

  1. Using Curly Braces {}:

fruits = {"Apple", "Banana", "Cherry"}
  1. Using the set() Function:

numbers = set([1, 2, 3, 4, 5])
  1. Empty Set:

empty_set = set()

Note: Using {} creates an empty dictionary, not a set. To create an empty set, always use set().

Accessing Elements in a Set

Sets are unordered, so you cannot access elements by index. However, you can iterate through a set:

fruits = {"Apple", "Banana", "Cherry"}
for fruit in fruits:
    print(fruit)

Because sets are unordered, the order of items may not match the order in which they were added.

Adding Elements to a Set

You can add elements to a set using the add() or update() methods:

  1. Adding a Single Element:

fruits.add("Mango")
  1. Adding Multiple Elements:

fruits.update(["Pineapple", "Grapes"])

Removing Elements from a Set

You can remove elements using several methods:

  • remove() – removes a specific element. Raises an error if the element does not exist:

fruits.remove("Banana")
  • discard() – removes a specific element. Does not raise an error if the element does not exist:

fruits.discard("Orange")  # No error
  • pop() – removes and returns an arbitrary element:

removed_item = fruits.pop()
  • clear() – removes all elements:

fruits.clear()

Set Operations

Python sets support mathematical operations, making them very useful for data analysis and problem-solving.

  1. Union – combines elements from two sets (duplicates removed):

set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
# Output: {1, 2, 3, 4, 5}
  1. Intersection – returns elements common to both sets:

common = set1.intersection(set2)
# Output: {3}
  1. Difference – returns elements in the first set but not in the second:

diff = set1.difference(set2)
# Output: {1, 2}
  1. Symmetric Difference – returns elements in either set but not in both:

sym_diff = set1.symmetric_difference(set2)
# Output: {1, 2, 4, 5}

Membership Testing

Sets are highly efficient for checking whether an element exists:

fruits = {"Apple", "Banana", "Cherry"}
print("Apple" in fruits)    # Output: True
print("Mango" not in fruits)  # Output: True

Set Methods

Some useful built-in set methods include:

  • copy() – returns a shallow copy of the set:

copy_set = fruits.copy()
  • isdisjoint() – checks if two sets have no elements in common:

set1 = {1, 2}
set2 = {3, 4}
print(set1.isdisjoint(set2))  # Output: True
  • issubset() – checks if a set is a subset of another:

set1 = {1, 2}
set2 = {1, 2, 3, 4}
print(set1.issubset(set2))  # Output: True
  • issuperset() – checks if a set contains all elements of another set:

print(set2.issuperset(set1))  # Output: True

Frozenset

Python also provides an immutable set called frozenset. You cannot add or remove elements from a frozenset. This is useful when you need a set that should not change:

immutable_set = frozenset([1, 2, 3])

Practical Examples with Sets

  1. Remove Duplicates from a List:

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)  # Output: {1, 2, 3, 4, 5}
  1. Finding Common Elements Between Two Lists:

list1 = [1, 2, 3]
list2 = [2, 3, 4]
common = set(list1).intersection(list2)
print(common)  # Output: {2, 3}
  1. Finding Unique Elements Across Lists:

all_elements = set(list1).union(list2)
  1. Checking Membership Efficiently:

fruits = {"Apple", "Banana", "Cherry"}
if "Apple" in fruits:
    print("Apple is in the set")
  1. Set Difference Example:

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
diff = set1.difference(set2)
print(diff)  # Output: {1, 2}

Summary of the Tutorial

Python sets are unordered, mutable, and unique collections of elements. They are particularly useful for eliminating duplicates, performing membership tests, and executing mathematical operations like union, intersection, and difference. Sets are a fundamental part of Python, and mastering them will make your programs more efficient and concise, especially when dealing with collections of data where uniqueness matters. Understanding sets also lays the groundwork for advanced topics like data analysis and algorithm design.


Practice Questions

  1. Create a set fruits containing "Apple", "Banana", and "Cherry" and print it.

  2. Add "Mango" to the set fruits.

  3. Add multiple elements "Pineapple" and "Grapes" to the set fruits.

  4. Remove "Banana" from the set fruits using remove() and then try discard() with a non-existent element.

  5. Create two sets set1 = {1, 2, 3} and set2 = {3, 4, 5} and find their union.

  6. Find the intersection of set1 and set2.

  7. Find the difference between set1 and set2 and then between set2 and set1.

  8. Find the symmetric difference of set1 and set2.

  9. Check if set1 is a subset of set2 and if set2 is a superset of set1.

  10. Convert a list with duplicate numbers [1, 2, 2, 3, 4, 4, 5] into a set to remove duplicates.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top