In this tutorial, we will learn how to make a set in Python. A set is an unordered and unindexed collection of unique elements, which means that it cannot contain duplicate elements.
Using sets can make certain types of operations such as intersection or union more efficient than using lists or arrays. Let’s dive into how to create a set in Python using various methods.
Step 1: Creating a Set Using Curly Braces
One way to create a set is by using curly braces and comma-separated elements. Place the unique elements inside the braces to create a set.
1 2 |
my_set = {1, 2, 3, 4} print(my_set) |
{1, 2, 3, 4}
Note: If you try to include duplicate elements, Python will automatically remove them and only store the unique elements.
Step 2: Creating a Set Using the Set Constructor
Another way to create a set is by using the set() constructor. You can pass a list, tuple, or other iterable types, such as strings, as an argument to the set() constructor.
1 2 3 |
my_list = [1, 2, 3, 4, 4] my_set = set(my_list) print(my_set) |
{1, 2, 3, 4}
As you can see, the duplicate value 4 from the list has been removed.
Step 3: Adding and Removing Elements from a Set
To add an element to the set, use the add() method. To remove an element, use the remove() method or the discard() method. The remove() method raises an error if the specified element is not found in the set, while discard() does not.
1 2 3 4 5 6 7 8 9 |
my_set = {1, 2, 3} my_set.add(4) print(my_set) my_set.remove(2) print(my_set) my_set.discard(5) # Will not raise an error if 5 is not found in the set print(my_set) |
{1, 2, 3, 4} {1, 3, 4} {1, 3, 4}
Step 4: Common Operations on Sets
You can perform common operations such as union, intersection, and difference on sets.
1 2 3 4 5 6 7 8 9 10 11 |
set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} # Union print(set1.union(set2)) # Intersection print(set1.intersection(set2)) # Difference print(set1.difference(set2)) |
{1, 2, 3, 4, 5, 6} {3, 4} {1, 2}
Python also supports set operations using special characters like |
for union, &
for intersection and -
for difference.
Here’s the full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
my_set = {1, 2, 3, 4} print(my_set) my_list = [1, 2, 3, 4, 4] my_set = set(my_list) print(my_set) my_set = {1, 2, 3} my_set.add(4) print(my_set) my_set.remove(2) print(my_set) my_set.discard(5) print(my_set) set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} print(set1.union(set2)) print(set1.intersection(set2)) print(set1.difference(set2)) |
Conclusion
In this tutorial, we learned how to create a set in Python using curly braces and the set()
constructor, as well as how to add and remove elements, and perform common set operations like union, intersection, and difference. Sets are a useful data structure when working with unique elements or sets, and they can provide efficient operations compared to lists or arrays.