Lesson 30 of 70 – Python Sets
43%

Python Sets

A set is a collection of items in Python that is unordered, unindexed, and does not allow duplicate values. Sets are useful when you need to store unique items.

Note: A set is created using curly braces { } or the set() constructor.
1. What is a Set?

A set stores multiple values in a single variable. Unlike lists and tuples, a set does not keep duplicate values.

numbers = {10, 20, 30, 40}

print(numbers)
Output:
{10, 20, 30, 40}
2. Creating a Set

You can create a set by placing values inside curly braces.

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

print(fruits)
Output:
{'apple', 'banana', 'mango'}

The order in which set elements are displayed should not be relied upon.

3. Sets Do Not Allow Duplicates

If you add the same value multiple times, a set keeps only one copy.

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

print(numbers)
Output:
{10, 20, 30, 40}
4. Set Is Unordered

Sets are unordered collections. Therefore, you should not depend on the display order of their elements.

colors = {"red", "green", "blue"}

print(colors)

The elements may be displayed in an order different from the order in which they were written.

5. Set Does Not Support Indexing

Because sets are unordered, you cannot access their elements using indexes.

numbers = {10, 20, 30}

print(numbers[0])
Result:
TypeError: 'set' object is not subscriptable
6. Creating a Set Using set()

You can also create a set using the set() constructor.

numbers = set([10, 20, 30, 40])

print(numbers)
Output:
{10, 20, 30, 40}
7. Creating an Empty Set

To create an empty set, use set().

my_set = set()

print(my_set)
Output:
set()

{} creates an empty dictionary, not an empty set.

8. Set vs Dictionary
empty_set = set()

empty_dictionary = {}

print(type(empty_set))
print(type(empty_dictionary))
Output:
<class 'set'>
<class 'dict'>
9. Sets Can Store Different Data Types

A set can contain values of different data types, provided the values are hashable.

data = {10, "Python", 20.5, True}

print(data)

The display order is not guaranteed.

10. Sets Cannot Contain Mutable Elements

Set elements must be hashable. For example, a list cannot be directly stored as an element of a set.

numbers = {[1, 2], [3, 4]}
Result:
TypeError: unhashable type: 'list'

Immutable values such as numbers, strings, and tuples can generally be used as set elements.

11. Finding the Length of a Set

Use the len() function to find the number of elements in a set.

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

print(len(fruits))
Output:
3
12. Checking an Element Using in

The in operator checks whether an element exists in a set.

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

print("apple" in fruits)
print("orange" in fruits)
Output:
True
False
13. Checking an Element Using not in

The not in operator checks whether an element is absent from a set.

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

print("orange" not in fruits)
Output:
True
14. Adding an Element to a Set

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

fruits = {"apple", "banana"}

fruits.add("mango")

print(fruits)
Output:
{'apple', 'banana', 'mango'}
15. Adding a Duplicate Element

Adding an element that already exists does not create a duplicate.

numbers = {10, 20, 30}

numbers.add(20)

print(numbers)
Output:
{10, 20, 30}
16. Removing an Element

The remove() method removes a specified element.

numbers = {10, 20, 30, 40}

numbers.remove(30)

print(numbers)
Output:
{10, 20, 40}

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

17. discard() Method

The discard() method also removes an element, but unlike remove(), it does not raise an error if the element is absent.

numbers = {10, 20, 30}

numbers.discard(50)

print(numbers)
Output:
{10, 20, 30}
18. clear() Method

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

numbers = {10, 20, 30}

numbers.clear()

print(numbers)
Output:
set()
19. Iterating Through a Set

You can use a for loop to access each element of a set.

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

for fruit in fruits:
    print(fruit)

The elements may be printed in any order because sets are unordered.

20. Practical Example: Removing Duplicates

One common use of sets is removing duplicate values from a list.

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

unique_numbers = set(numbers)

print(unique_numbers)
Output:
{10, 20, 30, 40}
21. Set Operations

Python sets support useful mathematical set operations such as:

  • Union – combines elements from sets.
  • Intersection – finds common elements.
  • Difference – finds elements present in one set but not another.
  • Symmetric Difference – finds elements present in either set but not both.

These operations will be covered in detail in the next lessons.

22. Set Example
students = {"Amit", "Rahul", "Priya", "Amit"}

print("Students:", students)
print("Total:", len(students))

if "Rahul" in students:
    print("Rahul is present")
Output:
Students: {'Amit', 'Rahul', 'Priya'}
Total: 3
Rahul is present
23. Key Points
  • A set is a collection of unique elements.
  • Sets are unordered.
  • Sets do not support indexing or slicing.
  • Duplicate values are automatically removed.
  • Use { } to create a non-empty set.
  • Use set() to create an empty set.
  • Use add() to add an element.
  • Use remove() or discard() to remove an element.
  • Use clear() to remove all elements.
  • Use in and not in to check membership.
  • Sets are useful for removing duplicates and performing set operations.

🧠 Quick Quiz

Question: Which feature is true about Python sets?