Creating Set
-
This lesson explains how to create sets in Python and store unique values.
A set in Python is a built-in data type used to store multiple unique values in a single variable.
Sets do not allow duplicate values
Sets are unordered (no fixed position)
Sets are mutable (you can add or remove items)
Written using curly braces {}
Daily Life Example
Think of a set like:
A collection of unique roll numbers in a class
Unique visitors on a website
Unique items in a shopping cart
If the same value appears twice, Python keeps only one copy.
Create a Set using Curly Braces {}
Basic Set Creation
fruits = {"apple", "banana", "mango"}
print(fruits)
Code Description:
A set named fruits is created.
Items are stored inside { }.
Order may change in output (sets are unordered).
Duplicate Values Are Removed Automatically
Set Removes Duplicates
numbers = {1, 2, 3, 2, 1}
print(numbers)
Code Description
Even though 1 and 2 appear twice, set keeps only unique values.
Output will contain only {1, 2, 3}.
Using set() Constructor
Used when converting other data types to a set.
letters = set(["a", "b", "c", "a"])
print(letters)
Code Description
A list is converted into a set.
Duplicate "a" is removed.
Creating an Empty Set
{} creates an empty dictionary, not a set.
Correct Way to Create Empty Set
empty_set = set()
print(type(empty_set))
Creating Set with Mixed Data Types
Set with Different Data Types
data = {10, "Python", True, 3.14}
print(data)
Important Rules of Sets
Elements must be immutable (no list or dictionary inside set)
No duplicate values allowed
Sets are faster for membership checking