Python Python Tutorial File Handling NumPy Tutorial NumPy Random NumPy ufunc Pandas Tutorial Pandas Cleaning Data Pandas Correlations Pandas Plotting SciPy Tutorial



Python Sets

Python sets are a built-in data type in Python that represent a collection of unique elements. Sets are unordered and mutable, which means that you can add or remove elements from a set after it has been created. In this article, we will explore the basics of Python sets and how to use them in your code.

Creating a Set

To create a set in Python, you can use the set() function or enclose a list of elements in curly braces {}. Here are some examples:

>>> my_set = set()
>>> my_set.add(1)
>>> my_set.add(2)
>>> my_set.add(3)
>>> print(my_set)
{1, 2, 3}

>>> my_set = {1, 2, 3}
>>> print(my_set)
{1, 2, 3}

As you can see, we can add elements to a set using the add() method, and we can also create a set directly by enclosing a list of elements in curly braces.

Operations on Sets

Python sets support a variety of operations, including union, intersection, difference, and symmetric difference. Here are some examples:

>>> set1 = {1, 2, 3}
>>> set2 = {2, 3, 4}
>>> print(set1.union(set2))
{1, 2, 3, 4}

>>> print(set1.intersection(set2))
{2, 3}

>>> print(set1.difference(set2))
{1}

>>> print(set1.symmetric_difference(set2))
{1, 4}

As you can see, we can perform various operations on sets using built-in methods like union(), intersection(), difference(), and symmetric_difference().

Iterating Over a Set

We can iterate over a set using a for loop, just like we would with a list or tuple. Here is an example:

>>> my_set = {1, 2, 3}
>>> for element in my_set:
...     print(element)
...
1
2
3

As you can see, we can use a for loop to iterate over the elements of a set.

Membership Testing

We can test whether an element is a member of a set using the in keyword. Here is an example:

>>> my_set = {1, 2, 3}
>>> print(2 in my_set)
True
>>> print(4 in my_set)
False

As you can see, we can use the in keyword to test whether an element is a member of a set.

Conclusion

Python sets are a powerful data type that allow you to represent a collection of unique elements. Sets support a variety of operations, including union, intersection, difference, and symmetric difference. We can iterate over a set using a for loop, and we can test whether an element is a member of a set using the in keyword.

References

Activity