What Is Set in Python | with Example  

Introduction

In this tutorial, we will learn what is set in Python with example and how to use it effectively. so Python sets are a versatile way to store unique items, perform operations like unions or intersections, and manage data efficiently

This guide is perfect for beginners who want hands-on Python examples, understand empty sets, and know the difference between sets and dictionaries. By the end, you’ll be confident using sets in your Python projects.

In Short

Python sets store unique, unordered elements. They allow easy data operations like union, intersection, and difference. Learn creation, conversion from lists, and differences from dictionaries in this guide. 

Understanding What Is Set in Python

set in Python is a collection of unique items. Unlike lists or tuples, sets cannot have duplicate elements and are unordered. 

Example:
# Creating a simple set 
fruits = {"apple", "banana", "cherry"} 
print(fruits)
Output: 
{'banana', 'cherry', 'apple'}

run this file in your IDE give the any filename and run it.

Note:

  • sets cannot have duplicate elements 
What Is Set in Python

why sets exist in Python

In Python, a set is a collection of unique items, which means it automatically removes duplicates. This makes sets perfect for situations where you only want to keep one copy of each item, like storing a list of unique usernames, email addresses, or product IDs. Unlike lists or tuples, sets are unordered, so the items don’t have a fixed position, and you don’t rely on their order when working with them.

Sets are also very efficient when checking if an item exists in the collection. For example, if you want to see whether a certain email has already been used, sets can perform this check much faster than a list. Additionally, sets support mathematical operations like union, intersection, and difference, allowing you to easily combine collections, find common items, or identify missing elements. These features make sets a powerful tool for organizing and comparing data in Python.

# Removing duplicate emails from a list
emails = ["a@example.com", "b@example.com", "a@example.com"]
unique_emails = set(emails)
print(unique_emails)

Output:

{'a@example.com', 'b@example.com'}

Tip: “Use sets when you only care about unique elements, not order.”

How to Define Set in Python

You can create a set in two main ways: using curly braces {} or the set() function. Curly braces are the most straightforward way if you already know the items you want to include

1.curly braces {}

# Creating a set of fruits
fruits = {"apple", "banana", "cherry"}

# Printing the set
print(fruits)

# Adding a new fruit
fruits.add("orange")
print(fruits)

# Removing a fruit
fruits.remove("banana")
print(fruits)

Output:

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

{'orange', 'banana', 'cherry', 'apple'}

{'orange', 'cherry', 'apple'}

If you don’t know the items in advance or want to convert another iterable like a list or tuple into a set, you can use the set() function. This is also useful for creating an empty set, which cannot be done with {} alone (because {} creates an empty dictionary).

2. Using set() function

# Using set() function
numbers = set([1, 2, 3, 4])
empty_set = set()
print(numbers)
print(empty_set)

Output:

{1, 2, 3, 4}
set()

You can also define sets with mixed data types, as long as the elements are hashable (immutable). For example, numbers, strings, and tuples can be included in the same set:

mixed_set = {1, "apple", (2, 3)}
print(mixed_set)

Output:

{1, (2, 3), 'apple'}

Note:
Sets in Python are easy to define, versatile, and useful for ensuring uniqueness, performing fast membership checks, and doing mathematical operations like union and intersection. Using curly braces is simple for predefined items, while set() is flexible for dynamic or empty sets

Creating an Empty Set in Python

An empty set in Python must be created with set(). 

# Empty set 
empty_set = set() 
print(empty_set)

Output:

set()

Tip: Don’t use {} for an empty set — that creates an empty dictionary.

Example of Set in Python

Here’s a practical example showing set operations

  1. Set Operation example
# Set operations 
a = {1, 2, 3} 
b = {3, 4, 5} 
 
print("Union:", a | b)         # Union of sets 
print("Intersection:", a & b)  # Common elements 
print("Difference:", a - b)    # Elements in a not in b

Output:

Union: {1, 2, 3, 4, 5} 
Intersection: {3} 
Difference: {1, 2}

Tip: Sets are useful for removing duplicates quickly.

difference between list set tuple and dictionary in python

2. Find length of set in python

In Python, you can find the length of a set (i.e., the number of elements in it) using the built-in len() function.

# Define a set
my_set = {10, 20, 30, 40, 50}

# Find the length of the set
length = len(my_set)

print("Length of the set:", length)

Output:

Length of the set: 5

Note:

  • Sets automatically remove duplicates, so len() will count only unique elements.
  • Works the same way as len() for lists, tuples, and dictionarie

Converting List to Set in Python

You can easily remove duplicates from a list by converting it to a set: 
Main Purpose : remove duplicates from list

my_list = [1, 2, 2, 3, 4, 4] 
unique_set = set(my_list) 
print(unique_set)

Output:

{1, 2, 3, 4}

Note: Converting back to a list may reorder elements.

Difference Between Dictionary and Set in Python

below are the difference between the dictionary and set which you clear the concept

Feature Set Dictionary 
Structure Unordered collection of unique items Key-value pairs 
Mutable Yes Yes 
Duplicate keys Not allowed Keys must be unique 
Syntax {1, 2, 3} {“a”: 1, “b”: 2} 

below are the example of it which you differentiate them

my_set = {1, 2, 3} 
my_dict = {"a": 1, "b": 2} 
print(my_set, my_dict)

Output:

{1, 2, 3} {'a': 1, 'b': 2}

Practical Tips for Python Sets

  • Use sets to remove duplicates quickly. 
  • Sets support mathematical operations: union, intersection, difference. 
  • Great for membership checks, faster than lists. 

FAQs

  1. Can sets store duplicate values? 
    No, sets only store unique elements. 
  1. Can a set contain different data types? 
    Yes, but all elements must be hashable
  1. How do I create an empty set? 
    Use set(), not {}. 
  1. Are sets ordered? 
    No, sets are unordered, so element order can change. 
  1. Can I convert a set back to a list? 
    Yes, using list(my_set); order is not guaranteed. 
  2. Can sets contain other sets? 
    No, sets are mutable and cannot be added to other sets. Use frozenset for nested sets. 
  3. How to remove items from a set? 
    Use remove() or discard(). discard() does not throw an error if the item doesn’t exist. 
  4. Can sets store unhashable types? 
    No, lists or dictionaries cannot be stored in sets. Only hashable types like numbers, strings, and tuples. 

More Tutorial

Leave a Reply

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