B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Sets Tutorial with Examples | LiveCodeProgramming

Python Sets Tutorial

A Set in Python is an unordered collection of unique elements. Sets are useful when you want to store non-duplicate items and perform mathematical operations like union, intersection, etc.

Python में Set एक unordered और unique elements का collection होता है। Set का उपयोग ऐसे data को store करने में किया जाता है जिसमें डुप्लीकेट न हों और mathematical operations जैसे union, intersection करना हो।

1. Creating a Set
my_set = {1, 2, 3, 4}
print(my_set)
Output:
{1, 2, 3, 4}
2. Add Elements
my_set.add(5)
print(my_set)
Output:
{1, 2, 3, 4, 5}
3. Remove Elements
my_set.remove(3)
print(my_set)
Output:
{1, 2, 4, 5}
4. Loop Through a Set
for item in my_set:
    print(item)
Output:
1
2
4
5
5. Union of Sets
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b))
Output:
{1, 2, 3, 4, 5}
6. Intersection of Sets
print(a.intersection(b))
Output:
{3}
7. Set Length
print(len(my_set))
Output:
4