Set operations are fundamental in Python, enabling you to manipulate and analyze data more efficiently. With W3Schools as our guide, let's explore set operations in Python with examples.

Before diving into set operations, it's crucial to understand what sets are. In Python, a set is an unordered collection of unique elements. They are defined using curly braces {} or the built-in set() function.

Creating and Understanding Sets
A simple way to create a set in Python is by listing elements enclosed in curly braces. Elements can be of different data types, but only unique items are stored.

You can also create a set from a list or tuple using the set() function. Let's see an example:
Creating a Set from List

List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] becomes Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
You can use set() function for conversion: set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Creating a Set using set() with List Comprehension

Set comprehension is a compact way to create sets. Here's an example:
{i: i**2 for i in range(1, 11)} will create a set: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Set Operations in Python

Now that we've created our sets, let's explore set operations using W3Schools as our reference.
Union Operation




















The union of two sets is a set that contains all unique elements from both sets.
To perform a union operation, you can use the union() method or the pipe '|' symbol:
Set1 = {1, 2, 3, 4, 5}
Set2 = {4, 5, 6, 7, 8}
Set1.union(Set2) or Set1 | Set2 results in: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection Operation
The intersection of two sets is a set that contains only the common elements from both sets.
You can use the intersection() method or the "&" symbol for this operation:
Set1 = {1, 2, 3, 4, 5}
Set2 = {4, 5, 6, 7, 8}
Set1.intersection(Set2) or Set1 & Set2 results in: {4, 5}
Difference Operation
The difference between two sets is a set that contains elements present in the first set but not in the second set.
Use the difference() method or the "-" symbol for this operation:
Set1 = {1, 2, 3, 4, 5}
Set2 = {4, 5, 6, 7, 8}
Set1.difference(Set2) or Set1 - Set2 results in: {1, 2, 3}
Symmetric Difference Operation
The symmetric difference of two sets is a set that contains elements unique to each set.
Use the symmetric_difference() method or the "^" symbol for this operation:
Set1 = {1, 2, 3, 4, 5}
Set2 = {4, 5, 6, 7, 8}
Set1.symmetric_difference(Set2) or Set1 ^ Set2 results in: {1, 2, 3, 6, 7, 8}
The power of set operations lies in their ability to simplify data analysis, filter information, and perform complex computations efficiently. Now that you've learned set operations in Python with the help of W3Schools, explore further to discover more about sets and their applications.