Set In Python Full Topic Explained With Detailed in Hindi | Python full Tutorial | Data Science | Data Analytics Tutorial | Data Analytics Course | Data Science Tutorial | Data Science Full Course for beginners in Hindi
In Python, a set is a collection of unique items. Unlike lists or tuples, sets do not have a specific order, and they do not allow duplicate elements.
Here are some key points about sets in Python:
Uniqueness: Sets can only contain unique elements. If you try to add a duplicate element to a set, it will simply ignore it.
No Order: Sets do not maintain the order of elements. When you add items to a set or iterate over it, you cannot rely on any specific order.
Mutable: Sets are mutable, meaning you can add or remove items after creating them.
Mathematical Operations: Sets support various mathematical operations like union, intersection, difference, and symmetric difference, which can be very useful in solving certain types of problems.
Hashable Elements: Elements in a set must be hashable. This means that they must be immutable (like numbers, strings, or tuples containing only immutable elements). Mutable objects like lists cannot be added to a set because their contents can change, which would affect their hash value.
Here's how you can create a set in Python:
python
Copy code
my_set = {1, 2, 3}
Or you can use the set() function:
python
Copy code
my_set = set([1, 2, 3])
To add elements to a set, you can use the add() method:
python
Copy code
my_set.add(4)
To remove elements, you can use the remove() method:
python
Copy code
my_set.remove(2)
And you can perform various operations on sets like union, intersection, etc. For example:
python
Copy code
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # {1, 2, 3, 4, 5}
intersection_set = set1.intersection(set2) # {3}
Sets are commonly used when you need to work with unique elements or perform mathematical operations on collections of data.