Python Sets: For Unique Collections

Introduction

Python sets are an incredibly useful data type in the Python programming language. A set is an unordered collection of unique elements that can be of any type, including numbers, strings, and even other sets. In this article, we will explore what sets are, how to create them, and how to use them in Python.

Creating Python Sets

To create a Python set, we use a pair of curly braces `{}` enclosing a comma-separated list of elements, or the built-in `set()` function:


# Creating a set using curly braces
fruits = {'apple', 'banana', 'orange'}

# Creating a set using set() function
vegetables = set(['carrot', 'broccoli', 'spinach'])

Note that sets are unordered, meaning their elements do not have a fixed position in memory. Additionally, since sets only store unique elements, any duplicates in the initial list or sequence are automatically removed.

Operations on Python Sets

Python sets support a variety of operations to manipulate and compare their elements. Here are some of the most common operations:

Adding Elements

To add a single element to a set, we use the `add()` method. To add multiple elements, we use the `update()` method with an iterable argument:


# Adding a single element to a set
fruits.add('pear')

# Adding multiple elements to a set
vegetables.update(['potato', 'tomato'])

Removing Elements

To remove an element from a set, we use the `remove()` or `discard()` method. The difference between these methods is that `remove()` will raise a `KeyError` if the element is not found, while `discard()` will silently do nothing:


# Removing an element from a set
fruits.remove('banana')

# Removing an element that may or may not be in the set
vegetables.discard('lettuce')

Set Operations

Python sets support a variety of set operations to compare and manipulate their elements. Here are some of the most common set operations:

  • Union: combines two sets, removing duplicates
  • Intersection: finds the elements common to both sets
  • Difference: finds the elements in one set but not the other
  • Symmetric Difference: finds the elements that are exclusively present in either of the two sets, and not in both.

# Union
all_produce = fruits.union(vegetables)

# Intersection
common_produce = fruits.intersection(vegetables)

# Difference
fruit_only = fruits.difference(vegetables)

# Symmetric difference
unique_produce = fruits.symmetric_difference(vegetables)

Set Membership

Python sets support the `in` and `not in` operators to check if an element is a member of a set:


# Membership check
if 'apple' in fruits:
    print('Found an apple!')

if 'celery' not in vegetables:
    print('No celery here.')

Common Use Cases for Python Sets

Python sets are useful in many different contexts, from simple data filtering to complex algorithmic problems. Here are a few common use cases:

Removing Duplicates

One of the most common use cases for sets is to remove duplicates from a list. Because sets are collections of unique elements, we can easily create a set from a list to remove any duplicates, and then convert it back to a list if needed.


my_list = [1, 2, 3, 2, 1, 4, 5, 4, 6]
unique_elements = set(my_list)
my_new_list = list(unique_elements)

In this example, `unique_elements` will contain the unique elements from `my_list`, and `my_new_list` will contain these unique elements in the same order as they appeared in the original list, but without any duplicates.

Finding Common Elements

Another common use case for sets is to find the common elements between two or more collections. We can use the `intersection()` method to get the common elements between two or more sets.


set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
common_elements = set1.intersection(set2)

In this example, `common_elements` will contain the elements 4 and 5, which are present in both `set1` and `set2`.

Checking Membership

We can also use sets to efficiently check if an element is present in a collection. We can use the `in` operator to check if an element is present in a set. This operation is much faster than checking if an element is present in a list, especially for large collections.


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

In this example, the `if` statement will evaluate to `True`, because element 3 is present in `my_set`.

Exercises

Here are some exercises for practicing Python sets:

  1. Write a Python program to create a set of integers from a given list and print the set.
  2. Write a Python program to add an item to a set and print the updated set.
  3. Write a Python program to remove an item from a set and print the updated set.
  4. Write a Python program to find the intersection of two sets and print the result.
  5. Write a Python program to find the union of two sets and print the result.
  6. Write a Python program to find the difference between two sets and print the result.
  7. Write a Python program to check if a given set is a subset of another set.
  8. Write a Python program to check if two sets have any common elements.
  9. Write a Python program to find the maximum and minimum value in a set.
  10. Write a Python program to clear a set and print the empty set.

These exercises should help you practice the different operations that can be performed on sets in Python. Good luck!

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 147