Python Sets – Complete Guide with Examples

Introduction

Python provides several built-in data structures that help developers store and manage collections of data. One of the most useful and unique data structures is the Set. Sets are used when you need to store multiple items while ensuring that every value is unique.

Note: sets do not allow duplicate values.

Sets are widely used in real-world applications such as data analysis, database processing, user management systems, and inventory tracking.

What is a Set in Python?

A Set is an unordered collection of unique items.

📖
Key characteristics:
  • Unordered
  • Mutable (can be modified)
  • Do not allow duplicate values
  • Can contain different data types
  • Not indexed

Example:


fruits = {"Apple", "Banana", "Mango"}
print(fruits)

Output:

{‘Apple’, ‘Banana’, ‘Mango’}

The order may vary because sets are unordered.

Why Use Sets?

Sets are useful when:

  • Removing duplicate values
  • Performing mathematical operations
  • Fast membership testing
  • Comparing collections of data
  • Storing unique records

Example:


numbers = {1, 2, 2, 3, 4, 4}
print(numbers)

Output:

{1, 2, 3, 4}

Duplicate values are automatically removed.

Syntax

Sets are created using curly braces {}.


set_name = {item1, item2, item3}

Example:


colors = {"Red", "Green", "Blue"}
print(colors)

Output:

{‘Red’, ‘Green’, ‘Blue’}

Creating a Set

1. Set of Numbers

Example:


numbers = {10, 20, 30, 40}
print(numbers)

Output:

{10, 20, 30, 40}

2. Set of Strings


fruits = {"Apple", "Banana", "Mango"}
print(fruits)

3. Mixed Data Types


data = {"John", 25, True, 99.5}
print(data)

Sets can contain multiple data types.

Creating an Empty Set

A common beginner mistake is using {}.

Incorrect:


empty_set = {}

This creates a dictionary, not a set.

Correct:


empty_set = set()
print(type(empty_set))

Output:

<class ‘set’>

Duplicate Values in Sets

Sets automatically remove duplicates.

Example:


numbers = {1, 2, 2, 3, 3, 4}
print(numbers)

Output:

{1, 2, 3, 4}

This feature makes sets ideal for removing duplicate data.

Accessing Set Items

Sets do not support indexing because they are unordered.

Incorrect:


fruits = {"Apple", "Banana", "Mango"}
print(fruits[0])

Output:

TypeError

Instead, use a loop.

Example:


fruits = {"Apple", "Banana", "Mango"}

for fruit in fruits:


print(fruit)

Checking if an Item Exists

Use the in operator.

Example:


fruits = {"Apple", "Banana", "Mango"}
print("Banana" in fruits)

Output:

True

Adding Items to a Set

Use the add() method.

Syntax


set_name.add(item)

Example:


fruits = {"Apple", "Banana"}
fruits.add("Mango")
print(fruits)

Output:

{‘Apple’, ‘Banana’, ‘Mango’}

Adding Multiple Items

Use the update() method.

Example:


fruits = {"Apple", "Banana"}
fruits.update(["Mango", "Orange"])
print(fruits)

Output:

{‘Apple’, ‘Banana’, ‘Mango’, ‘Orange’}

Removing Items from a Set

Use the remove() method.

Example:


fruits = {"Apple", "Banana", "Mango"}
fruits.remove("Banana")
print(fruits)

Output:

{‘Apple’, ‘Mango’}

Using discard()

Unlike remove(), discard() does not generate an error if the item does not exist.

Example:


fruits = {"Apple", "Banana"}
fruits.discard("Orange")
print(fruits)

Output:

{‘Apple’, ‘Banana’}

Using pop()

The pop() method removes a random item.

Example:


fruits = {"Apple", "Banana", "Mango"}
removed = fruits.pop()
print(removed)
print(fruits)

Since sets are unordered, the removed item may vary.

Clearing a Set

Use the clear() method.

Example:


fruits = {"Apple", "Banana"}
fruits.clear()
print(fruits)

Output:

set()

Set Methods

Method Description
add() Adds an item
update() Adds multiple items
remove() Removes a specified item
discard() Removes an item safely
pop() Removes a random item
clear() Removes all items
copy() Creates a copy of the set

Set Union

Union combines all unique elements from two sets.

Example:


set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result)

Output:

{1, 2, 3, 4, 5}

Set Intersection

Intersection returns common elements.

Example:


set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.intersection(set2))

Output:

{2, 3}

Set Difference

Difference returns items present in one set but not the other.

Example:


set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.difference(set2))

Output:

{1}

Symmetric Difference

Returns elements that are unique to each set.

Example:


set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.symmetric_difference(set2))

Output:

Real-Life Example

Suppose a website stores user email addresses.


emails = {
    "user1@example.com",
    "user2@example.com",
    "user1@example.com"
}
print(emails)

Output:

{‘user1@example.com’, ‘user2@example.com’}

Duplicate email addresses are automatically removed.

This makes sets useful in registration systems and database cleanup tasks.

Set vs List

Feature Set List
Syntax {} []
Ordered No Yes
Duplicates Not Allowed Allowed
Indexed No Yes
Mutable Yes Yes
Search Speed Faster Slower

Advantages of Sets

  • Automatically remove duplicates
  • Fast membership testing
  • Efficient mathematical operations
  • Easy comparison of collections
  • Useful for large datasets

Common Mistakes

1. Using {} for an Empty Set

Incorrect:


my_set = {}

Creates a dictionary.

Correct:


my_set = set()

2. Trying to Access by Index

Incorrect:


numbers = {1, 2, 3}
print(numbers[0])

Sets do not support indexing.

3. Using remove() for Missing Items


fruits = {"Apple", "Banana"}
fruits.remove("Orange")

Error:

KeyError

Use discard() if the item may not exist.

4. Expecting Ordered Output


numbers = {1, 2, 3, 4}

Do not assume items will appear in the same order every time.

Best Practices

1. Use Sets When:

  • Removing duplicates
  • Comparing collections
  • Performing union and intersection operations
  • Fast searching is required

2. Use Lists When:

  • Order matters
  • Indexing is needed
  • Duplicate values are allowed

Conclusion

Python sets are powerful data structures designed for storing unique values and performing efficient collection-based operations. They automatically remove duplicates, provide fast membership testing, and support mathematical operations such as union, intersection, difference, and symmetric difference.

Sets are widely used in real-world applications such as user management systems, data analysis, inventory tracking, and database processing.

Python Sets – Interview Questions

Q 1: What is a set in Python?
Ans: A set is an unordered collection of unique elements.
Q 2: Can sets contain duplicate elements?
Ans: No, sets automatically remove duplicates.
Q 3: Are sets mutable?
Ans: Yes, but elements themselves must be immutable.
Q 4: How do you create a set?
Ans: Using curly braces {1, 2, 3} or set() constructor.
Q 5: Can sets be indexed?
Ans: No, sets do not support indexing or slicing.

Python Sets – Objective Questions (MCQs)

Q1. Which of the following correctly creates a set in Python?






Q2. Which of the following statements about sets is true?






Q3. What will be the output of the following code?

s = {1, 2, 2, 3, 3, 3}
print(s)






Q4. Sets in Python cannot contain which of the following data types?






Q5. What will type({}) return in Python?






Related Python Tutorials