0
0
Pythonprogramming~5 mins

Why sets are used in Python

Choose your learning style9 modes available
Introduction

Sets are used to store unique items and to quickly check if something is in a group. They help remove duplicates and make some tasks faster.

When you want to remove duplicate items from a list of things.
When you need to check if an item exists in a collection quickly.
When you want to find common items between two groups.
When you want to combine two groups but keep only unique items.
When you want to find items that are in one group but not in another.
Syntax
Python
my_set = {item1, item2, item3}
# or
my_set = set([item1, item2, item3])

Sets use curly braces {} or the set() function to create.

Items in a set are unique and unordered.

Examples
Create a set of fruits with unique names.
Python
fruits = {'apple', 'banana', 'orange'}
Creates a set from a list with duplicates; duplicates are removed.
Python
numbers = set([1, 2, 2, 3, 4])
print(numbers)
Finds common items between two sets using & operator.
Python
a = {1, 2, 3}
b = {2, 3, 4}
common = a & b
print(common)
Sample Program

This program shows how sets remove duplicates, check membership, and perform union, intersection, and difference operations.

Python
items = ['apple', 'banana', 'apple', 'orange', 'banana']
unique_items = set(items)
print('Unique items:', unique_items)

if 'apple' in unique_items:
    print('Apple is in the set')

set_a = {1, 2, 3}
set_b = {3, 4, 5}
print('Union:', set_a | set_b)
print('Intersection:', set_a & set_b)
print('Difference:', set_a - set_b)
OutputSuccess
Important Notes

Sets do not keep the order of items like lists do.

You cannot have mutable items like lists inside a set.

Sets are very fast for checking if an item exists.

Summary

Sets store unique items only.

They help remove duplicates easily.

Sets support fast membership tests and set operations like union and intersection.