Skip to main content

Python Sets: Definition, Properties, and Examples

 

✍️Introduction

In Python, a set is used to store multiple values in a single variable, just like lists and tuples.

But sets are unordered, unindexed, and do not allow duplicate values.

  • Sets are written using curly braces {}.
  • They automatically remove duplicate values.
  • Since they are unordered, elements do not have a fixed position.
  • Sets are useful for mathematical operations like union, intersection, and difference. 

📌This article will help you understand:

  • What is a set

  • How to create sets

  • Set properties

  • Set operations with examples

Note:Sets are commonly used when you need unique values and fast operations.

What is a Set in Python?

A set is a collection of unique (no duplicate) elements written inside curly brackets {}.

  • Sets do not allow duplicate values.
  • They are unordered, so elements do not have a fixed position.
  • Sets are unindexed, so we cannot access elements using index numbers.
  • They are useful for storing unique data and performing set operations.

Example:

numbers = {1, 2, 3, 4} # Create a set with unique elements print(numbers) # Print the set

Output (order may vary):
{1, 2, 3, 4}

"Code executed successfully" 

Note:Even if you add duplicate values, sets will automatically remove duplicates.

Creating a Set :

A set is created using curly brackets {} with comma-separated values.

  • Sets store unique values only.
  • They can contain different data types.
  • Duplicate values are automatically removed.
  • Sets are unordered, so output order may change.
Syntax:
set_name = {value1, value2, value3}

Example 1: Simple Set:

fruits = {"Apple", "Banana", "Mango"} # Create a set of fruits print(fruits) # Print the set
Output(order may vary):
{'Apple', 'Banana', 'Mango'}

"Code executed successfully" 

Example 2: Set with Different Data Types:

data = {10, "Python", 3.5, True} # Set with multiple data types print(data) # Print the set

Output (order may vary):

{10, 'Python', 3.5, True}
"Code executed successfully" 

Note:Sets automatically remove duplicates and do not maintain order.

Duplicate Values Not Allowed:

Sets do not allow duplicate values; only unique elements are stored.

  • When duplicate values are added, Python automatically removes them.
  • This makes sets useful for storing unique data.
  • Duplicate removal happens automatically during creation.
Example:

nums = {1, 2, 2, 3, 4} # Duplicate value 2 is added
print(nums) # Print the set (duplicates removed)

Output:
{1, 2, 3, 4}
"Code executed successfully" 

Note:Sets ensure all elements are unique without extra code.

Unordered and Unindexed

  • No index numbers

  • Order may change

❌ Invalid:

print(fruits[0])

Creating an Empty Set

❌ Wrong:

myset = {}

✅ Correct:

myset = set()


Set Length

print(len(fruits))

Adding Elements to a Set

fruits.add("Orange")

Add multiple items:

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

Removing Elements from a Set

fruits.remove("Banana") # Error if not found fruits.discard("Apple") # No error fruits.pop() # Removes random element

Looping Through a Set

for fruit in fruits: print(fruit)

Set Methods (Common)

Method              Description
add()Add element
update()Add multiple
remove()Remove element
discard()           Remove without error
pop()Remove random
clear()Remove all
copy()Copy set

Set Operations

Union

A = {1, 2, 3} B = {3, 4, 5} print(A | B)

Intersection

print(A & B)

Difference

print(A - B)

Symmetric Difference

print(A ^ B)

Checking Membership

print("Apple" in fruits)


Convert Set to List

mylist = list(fruits)


Difference Between List, Tuple, and Set

Feature         List      Tuple     Set
OrderedYesYesNo
ChangeableYesNoYes
DuplicatesYesYesNo
IndexingYesYesNo

When to Use Sets?

  • Remove duplicate values

  • Perform mathematical operations

  • Fast membership checking


Real-Life Example

emails = {"a@gmail.com", "b@gmail.com", "a@gmail.com"} print(emails)


❌ Common Mistakes

  • Using {} for empty set

  • Expecting order in output

  • Using index values


Conclusion

Sets are powerful and efficient data structures in Python.
They are best when you need unique data and fast operations.


💬 Quick Question


What will be the output?

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

Comment your answer 👇😊


📌 Related Articles:


Comments

popular

What Is Python Programming? Features, Uses and Career Scope.

  ✍️ Introduction Python is one of the most popular and beginner-friendly programming languages in the world today. It is widely used for web development, data science, artificial intelligence, automation, and software development. Because of its simple syntax and powerful features, Python is an excellent choice for students, beginners, and professionals. In this article, you will learn what Python programming is, its key features, real-life uses, and the career opportunities it offers. 🧠 What Is Python Programming? Python is a high-level, interpreted programming language created to make coding easy and readable. It allows developers to write programs using simple English-like statements, which makes it ideal for beginners. Python supports multiple programming styles such as procedural, object-oriented, and functional programming. ⭐ Features of Python Easy to learn and understand Simple and readable syntax Interpreted language Platform independent Large standard l...

what is Python Date and Time ? Complete Guide with Examples:

  ✍️ Introduction Python provides powerful tools to work with dates and times . The most commonly used module is datetime . The datetime module allows Python programs to create, manipulate, format, and perform calculations with dates and times easily. Date and time handling is used in: Logging systems Attendance & billing systems Data analysis Real-time applications How To Import Date and Time Module : In Python, the datetime module is used to work with dates , times , and date–time combinations . It is part of Python’s standard library, so no installation is required. You can import it in different ways depending on your need. import datetime Get Current Date and Time: This code obtains the current system date and time as a single datetime object using the datetime module. Example: import datetime now = datetime.datetime.now() print (now) Output: 2026-02-13 11:25:53.445827 "Code executed successfully"  Get Only Date: This code retrieves t...

Features of Python Programming Language Explained with Examples

✍️ Introduction Python is one of the most popular programming languages because of its powerful and easy-to-use features. It is designed to make programming simple, readable, and efficient. Python is widely used by beginners as well as professionals due to its flexibility and strong community support. In this article, we will discuss the main features of Python programming language in simple English with easy examples. 🧠 What Are Features of Python? Features of Python are the special characteristics that make it different from other programming languages. These features help programmers write clean, readable, and efficient code with less effort. ⭐ Key Features of Python Programming Language 1️⃣ Easy to Learn and Easy to Use Python has a simple syntax that is close to the English language. This makes it very easy for beginners to learn and understand programming concepts. Example: print("Hello, World!") 2️⃣ Interpreted Language Python is an interpreted language, which me...