Python sets are an unordered collection of unique elements.
They are useful for removing duplicates, performing mathematical operations like union and intersection, and handling membership tests efficiently in Python.
Creating a Set
You can create a set using curly braces {}
or the set()
function:
# Creating a set with curly braces
my_set = {1, 2, 3, 4, 5}
print(my_set)
# Creating a set using the set() function
another_set = set([1, 2, 2, 3, 4])
print(another_set)
Output:
{1, 2, 3, 4, 5}
{1, 2, 3, 4} # Duplicates are removed
Adding and Removing Elements
You can add elements to a set using add()
, and remove elements using remove()
or discard()
:
my_set.add(6)
print(my_set)
my_set.remove(3)
print(my_set)
my_set.discard(10) # No error if element does not exist
Explanation:
add()
inserts a new element.remove()
removes an element but raises an error if it doesn’t exist.discard()
removes an element but does not raise an error if it's missing.
Set Operations
Python sets support common mathematical operations. You can use either bitwise operators (|
, &
, -
, ^
) or their corresponding set methods (union()
, intersection()
, difference()
, symmetric_difference()
).
1. Union (|
or union()
)
What it does: Combines all unique elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # Using the | operator
print(set1.union(set2)) # Using the union() method
Output:
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
2. Intersection (&
or intersection()
)
What it does: Returns only the elements present in both sets.
print(set1 & set2)
print(set1.intersection(set2))
Output:
{3}
{3}
3. Difference (-
or difference()
)
What it does: Returns elements in set1
that are not in set2
.
print(set1 - set2)
print(set1.difference(set2))
Output:
{1, 2}
{1, 2}
4. Symmetric Difference (^
or symmetric_difference()
)
What it does: Returns elements that are in either set1
or set2
, but not in both.
print(set1 ^ set2)
print(set1.symmetric_difference(set2))
Output:
{1, 2, 4, 5}
{1, 2, 4, 5}
Difference Between Bitwise Operators and Methods
-
Bitwise operators (
|
,&
,-
,^
) are shorter and often used for quick set operations. -
Methods (
union()
,intersection()
, etc.) are more explicit and readable, especially in complex code.
Example comparison:
# Using bitwise operators
result1 = set1 | set2 # Union
result2 = set1 & set2 # Intersection
# Using methods
result3 = set1.union(set2)
result4 = set1.intersection(set2)
Both approaches produce the same results, but method calls can be more readable for beginners.
Checking Membership
Use the in
keyword to check if an element is in a set:
print(2 in set1) # True
print(6 in set1) # False
Set Comprehension
You can create sets using set comprehensions:
squared_set = {x**2 for x in range(1, 6)}
print(squared_set)
Output:
{1, 4, 9, 16, 25}
Key Takeaways
-
Sets store unique elements and are unordered.
-
Use
add()
,remove()
, anddiscard()
to modify sets. -
Perform mathematical operations with
union()
,intersection()
, anddifference()
. -
Use bitwise operators for quick operations and set methods for readability.
-
Sets provide fast membership testing and efficient duplicate removal in your Python projects.
Practice Exercise
Here's a simple challenge, open up your Python editor and try to write a program that finds common elements between two lists using sets:
def find_common_elements(list1, list2):
return set(list1) & set(list2)
print(find_common_elements([1, 2, 3, 4], [3, 4, 5, 6]))
Wrapping Up
Python sets are a powerful way to store unique elements and perform set operations efficiently. By understanding how to create, modify, and manipulate sets, you can enhance your data processing and problem-solving skills. Happy coding!