topic Set ,what is set, all topic theory + code python , powerful programming language CSM Skills

Опубликовано: 20 Июнь 2026
на канале: CSM Skills
12
0

topic Set ,what is set, all topic theory + code python ,power full languages csm skills
Python Sets - Complete Guide
A set in Python is an unordered, mutable, and unindexed collection of unique elements. It is used when we need to store multiple items in a single variable but do not allow duplicate values.

1. What is a Set in Python?
A set is a built-in data structure in Python that:

Stores unique elements (no duplicates).
Is unordered (no indexing).
Is mutable (can be changed after creation).
Is implemented using a hash table, making operations like searching, inserting, and deleting very fast.
Syntax:

python
Copy
Edit
Creating a set
my_set = {1, 2, 3, 4, 5}
print(my_set)
📌 Note: Sets are defined using curly braces {} or the set() function.

2. Creating a Set
There are multiple ways to create a set.

2.1 Using Curly Braces {}
python
Copy
Edit
fruits = {"apple", "banana", "cherry"}
print(fruits)
2.2 Using set() Constructor
python
Copy
Edit
numbers = set([1, 2, 3, 4, 5]) # Creating from a list
print(numbers)
2.3 Creating an Empty Set
python
Copy
Edit
empty_set = set() # Correct way
print(type(empty_set))
📌 Note: {} creates an empty dictionary, not a set.

3. Set Properties
Unordered → No specific order.
Unindexed → Cannot access elements by index.
No Duplicates → Only unique values are stored.
Mutable → We can add or remove elements.
Example:

python
Copy
Edit
s = {1, 2, 3, 3, 4, 5}
print(s) # Output: {1, 2, 3, 4, 5} (Duplicates removed)
4. Basic Set Operations
4.1 Adding Elements
We can add elements using add().

python
Copy
Edit
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # {1, 2, 3, 4}
4.2 Removing Elements
Using remove() (Throws an error if the element doesn’t exist)
Using discard() (Doesn’t throw an error)
Using pop() (Removes a random element)
python
Copy
Edit
s = {1, 2, 3, 4}
s.remove(3)
print(s) # {1, 2, 4}

s.discard(10) # No error even if 10 is not in the set
s.pop() # Removes a random element
4.3 Clearing a Set
python
Copy
Edit
s.clear() # Removes all elements
print(s) # Output: set()
5. Set Operations (Mathematical)
5.1 Union (| or union())
python
Copy
Edit
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # {1, 2, 3, 4, 5}
or

python
Copy
Edit
print(A.union(B))
5.2 Intersection (& or intersection())
python
Copy
Edit
print(A & B) # {3}
print(A.intersection(B))
5.3 Difference (- or difference())
python
Copy
Edit
print(A - B) # {1, 2}
print(A.difference(B))
5.4 Symmetric Difference (^ or symmetric_difference())
python
Copy
Edit
print(A ^ B) # {1, 2, 4, 5}
print(A.symmetric_difference(B))
6. Set Membership
We can check if an element exists in a set.

python
Copy
Edit
s = {1, 2, 3, 4}
print(2 in s) # True
print(5 in s) # False
7. Set Iteration
We can loop through a set using a for loop.