How to create a set in Python?
Table of Contents
Introduction
Sets are a built-in data type in Python that store unique elements. Unlike lists or tuples, sets automatically handle duplicate values by ensuring that each element appears only once. Sets are useful for operations involving membership tests, removing duplicates, and performing mathematical operations like unions and intersections.
Creating Sets in Python
Using Curly Braces
The most straightforward way to create a set in Python is by using curly braces {}
. Here’s how you can define a set:
This code snippet creates a set containing the integers 1 through 5. Note that the order of elements in a set is not guaranteed to be preserved.
Using the set()
Constructor
You can also create a set using the set()
constructor. This method is useful when you want to convert other iterables (like lists or tuples) into a set:
In these examples, duplicates are removed from the list and tuple, resulting in sets {1, 2, 3, 4}
.
Practical Examples
Example : Removing Duplicates from a List
In this example, converting the list to a set removes duplicate values.
Example : Set Operations
Sets support various mathematical operations like union, intersection, and difference:
Conclusion
Creating and working with sets in Python is straightforward and provides powerful tools for handling unique collections of data. Whether you’re removing duplicates from a list or performing complex mathematical operations, sets are a versatile and essential part of Python programming.