Tutorial

Sets in Python

6 min read

Set in Python is a collection of unique and unordered elements, which can be of any data type like integers, strings, or even other sets. The set data type is incredibly powerful in Python and is widely used in data manipulation, algorithm development, and mathematical operations.

In this post, we’ll explore the fundamentals of sets in Python. It will also include how to create, modify, and manipulate Python sets using built-in methods and operations.

Moreover, we will learn its advanced topics, such as set operations like intersection, union, and difference, and we’ll show how to perform set comprehension in Python.

Creating Sets in Python

Creating a set in Python is pretty straightforward.

We can create a set in Python by enclosing a comma-separated sequence of elements in curly braces {}.

For example, to create a set of integers in Python, we can write:

my_set = {1, 2, 3, 4, 5}

Alternatively, we can use the built-in set() function to create a set.

For instance, the following code creates a set of strings in Python:

my_set = set(["apple", "banana", "cherry"])

Note: When using the set() function, we need to pass an iterable (e.g., a list, tuple, or string) as an argument.

Modifying Sets in Python

Once we have created a set, we can modify it in various ways.

One way to modify sets in Python is to add or remove elements from them.

To add an element to a set, we can use the add() method, like this:

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # Output: {1, 2, 3, 4}

To remove an element from a Python set, we can use the remove() method, like this:

my_set = {1, 2, 3, 4}
my_set.remove(3)
print(my_set)  # Output: {1, 2, 4}

If we’re not sure whether an element exists in a  Python set, we can use the in keyword to check for its presence, like this:

my_set = {1, 2, 3, 4}
if 3 in my_set:
    print("3 is in the set")
else:
    print("3 is not in the set")

Built-in Functions in Set in Python

There are several built-in functions that we can use with sets in Python. Here are some of the most commonly used ones:

  • len(): Returns the number of elements in a set.
  • min(): Returns the smallest element in a set.
  • max(): Returns the largest element in a set.
  • sum(): Returns the sum of all elements in a set (works only with numerical values).
  • sorted(): Returns a sorted list of the elements in a set.
  • any(): Returns True if any element in the set is true. If the set is empty, it returns False.
  • all(): Returns True if all elements in the set are true. If the set is empty, it returns True.

Set Operations in Python

Sets in Python 3 support various operations, including mathematical set operations like – union, intersection, and difference.

In this section, we’ll explore how to perform these operations on sets in Python.

  • Union: The union of two sets is a set containing all the elements from both sets, without any duplicates. We can use the union() method or the pipe | operator to perform the union operation.

Example of union operation in Python sets:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)  # Output: {1, 2, 3, 4, 5}
# Alternatively:
union_set = set1 | set2
print(union_set)  # Output: {1, 2, 3, 4, 5}
  • Intersection: The intersection of two sets is a set containing only the elements that are common to both sets. We can use the intersection() method or the ampersand & operator to perform the intersection operation.

Example of Intersection in Python sets:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set)  # Output: {3}
# Alternatively:
intersection_set = set1 & set2
print(intersection_set)  # Output: {3}
  • Difference: The difference between two sets is a set containing only the elements that are in the first set but not in the second set. We can use the difference() method or the minus - operator to perform the difference operation.

Example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set)  # Output: {1, 2}
# Alternatively:
difference_set = set1 - set2
print(difference_set)  # Output: {1, 2}
  • Symmetric Difference: The symmetric difference between two sets is a set containing only the elements that are in either of the sets but not in both. We can use the symmetric_difference() method or the caret ^ operator to perform the symmetric difference operation.

Example of symmetric difference in Python sets:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)  # Output: {1, 2, 4, 5}
# Alternatively:
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set)  # Output: {1, 2, 4, 5}

Set Comprehension in Python

Set comprehension is a concise way to create a set in Python. It allows us to create a set by iterating over an iterable and applying a condition to each element.

Here’s the basic syntax for set comprehension in Python:

{expression for item in iterable if condition}
  • expression is the operation we want to perform on each element to create the set.
  • item is the variable that represents each element in the iterable.
  • iterable is the sequence of elements we want to iterate over.
  • condition is an optional condition that filters the elements.

Let’s take a look at some examples of Python set comprehension.

  • Creating a Python set of even numbers from 0 to 10:
my_set = {x for x in range(11) if x % 2 == 0}
print(my_set)  # Output: {0, 2, 4, 6, 8, 10}
  • Creating a Python set of the first letters of a list of words:
words = ['apple', 'banana', 'cherry', 'date']
my_set = {word[0] for word in words}
print(my_set)  # Output: {'a', 'b', 'c', 'd'}
  • Creating a Python set of the common elements in two lists:
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
my_set = {x for x in list1 if x in list2}
print(my_set)  # Output: {3, 4, 5}

Conclusion

In conclusion, sets are an important data structure in Python that allows us to store and manipulate unique collections of data efficiently.

We can create and modify Python sets using various built-in methods and operators. Also, we saw how to perform mathematical set operations such as union, intersection, difference, and symmetric difference on sets to manipulate them.

Sets can be created using set comprehension, which involves iterating over an iterable and applying a condition to each element. This provides a simple and effective method for creating sets in Python.

One important thing to keep in mind when working with sets is that they are unordered and unindexed, meaning we cannot access their elements by index or using slicing operations on them.

However, this property also means that Python sets can be extremely fast for checking if an item is in the set, as it takes constant time, regardless of the size of the set.

Overall,  Python sets are a useful and powerful feature that can help us solve many problems, from removing duplicates in a list to finding common elements in multiple lists.