Python Sets: Beginner Python tutorials 8 | Better4Code
Python Sets: Python is a powerful programming language that provides a range of data structures to organize and manipulate data. One such data structure is sets. Sets are an unordered collection of unique elements in Python. In this article, we will discuss how to use sets in Python with examples.
Creating Python Sets
You can create a set in Python by enclosing elements in curly braces {} separated by commas. Here’s an example:
my_set = {1, 2, 3, 4, 5}
In this example, we have created a set of integers with five elements.
Alternatively, you can also create a set by using the set() function and passing a list or tuple of elements. Here’s an example:
my_set = set([1, 2, 3, 4, 5])
In this example, we have created a set using the set() function.
Adding and Removing Elements
You can add an element to a set using the add() method. Here’s an example:
my_set = {1, 2, 3, 4, 5}
my_set.add(6)
print(my_set)
Output:
{1, 2, 3, 4, 5, 6}
In this example, we have added element 6 to the set using the add() method.
You can also remove an element from a set using the remove() method. Here’s an example:
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set)
Output:
{1, 2, 4, 5}
In this example, we have removed element 3 from the set using the remove() method.
Python Sets Operations
Sets support various operations such as union, intersection, difference, and symmetric difference. Here’s an example of each operation:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union
union_set = set1.union(set2)
print(union_set)
# Intersection
intersection_set = set1.intersection(set2)
print(intersection_set)
# Difference
difference_set = set1.difference(set2)
print(difference_set)
# Symmetric Difference
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3}
{1, 2, 3, 6, 7, 8}
In this example, we have performed each set operation on two sets set1 and set2.
Python Sets Comprehension
Like lists and dictionaries, sets also support comprehension. Here’s an example:
my_set = {x**2 for x in range(1, 6)}
print(my_set)
Output:
{1, 4, 9, 16, 25}
In this example, we have used set comprehension to create a set of squares of numbers from 1 to 5.
Conclusion
Python Sets are an important data structure in Python that allows you to store unique elements and perform various set operations. In this article, we have discussed how to create sets, add and remove elements, perform set operations, and use set comprehension. By mastering the usage of sets, you can write more efficient and effective Python code for various applications.