A set is a collection in Python that stores unique items. Unlike lists, sets don’t keep track of the order of elements, and they automatically remove any duplicates. So, if you add the same item to a set more than once, only one copy will stay!
Creating Sets
You can create a set by putting items inside curly braces {}
set()
# Using curly braces
my_set = {1, 2, 3, 4}
# Using set() function (to create an empty set)
empty_set = set()
Adding and removing elements
You can add elements to a set using the add()
remove()
# Adding an element
my_set.add(5)
# Removing an element
my_set.remove(3)
If you try to remove an element that doesn’t exist in the set, it will give an error. To avoid that, you can use discard()
my_set.discard(10) # Won't give an error even if 10 is not in the set
Set operations
Sets have some useful operations that let you combine or compare sets:
-
Union:
or|
: Combines two sets, keeping all unique elements from both.union()
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1 | set2 # Or you can use set1.union(set2) # Result: {1, 2, 3, 4, 5}
-
Intersection:
or&
: Returns only the items that appear in both sets.intersection()
intersection_set = set1 & set2 # Or you can use set1.intersection(set2) # Result: {3}
-
Difference:
or-
: Returns items in the first set but not in the second.difference()
difference_set = set1 - set2 # Or you can use set1.difference(set2) # Result: {1, 2}
Removing duplicates from Lists
Since sets only store unique elements, you can use a set to remove duplicates from a list. Simply convert the list to a set and then back to a list.
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(my_list))
# Result: [1, 2, 3, 4, 5] (order is not guaranteed)
Summary
- Sets store unique elements and don't care about the order.
- You can add and remove items, but there’s no index like in lists.
- Set operations like union, intersection, and difference let you work with multiple sets.
- You can remove duplicates from a list by converting it to a set.