Sets in Python
Sets are a fundamental data structure in Python that allow you to store a collection of unique items. They are used to perform set operations such as union, intersection, and difference on data sets. Sets are implemented as an unordered collection of unique elements and can be manipulated using various built-in methods. In this article, we will explore sets in Python and provide some practical examples to demonstrate their use.
Creating a Set in Python
To create a set in Python, you can use curly braces or the set() function. Here's an example of creating a set of fruits using curly braces:
Here's an example of creating the same set using the set() function:
Both of these methods will create the same set of fruits with three unique elements. If you try to add a duplicate element to the set, it will not be added since sets only contain unique elements.
Set Operations in Python
Sets allow you to perform various set operations such as union, intersection, and difference. Here are some examples of how to use these operations in Python:
The union operation combines two sets and returns a new set with all the unique elements from both sets.
The intersection operation returns a new set that contains only the elements that are common to both sets.
The difference operation returns a new set that contains only the elements that are in one set but not the other.
Other Set Operations:
Sets also have other built-in methods such as add(), remove(), and discard() for adding and removing elements from a set. Here are some examples of how to use these methods:
Iterating Over a Set in Python
You can iterate over a set using a for loop in Python. Here's an example:
Sets are a powerful data structure in Python that allow you to store a collection of unique elements and perform various set operations on them. They are easy to create and manipulate using built-in methods, and can be iterated over using a simple for loop. By understanding sets and their operations, you can write more efficient and concise code in Python.