PYTHON

Python Set: Working with Sets in Python

In Python, a set is a data type that consists of an unordered collection of unique items. Lists can include items (or elements) of any data type, including numbers, strings, dictionaries, functions, and lists.

How to Use Sets in Python

Python Creating Sets

To create a set in Python, you can use curly braces ({}) or the set() function.

# Using curly braces
my_set = {1, 2, 3, 4, 4}
print(my_set)  # Outputs: {1, 2, 3, 4}

# Using set() function
another_set = set([1, 2, 2, 3, 4])
print(another_set)  # Outputs: {1, 2, 3, 4}

Python Adding to Sets

You can add an element to a set using the add() method, passing the element as an argument. If the element already exists within the set, the set remains unchanged.

# Adding an element
my_set.add(5)
print(my_set)  # Outputs: {1, 2, 3, 4, 5}

You can also add multiple elements to a set using the update() method, passing a sequence as an argument.

my_set = {1, 2, 3}
my_set.update([4, 5, 6])
print(my_set)  # Outputs: {1, 2, 3, 4, 5, 6}

Python Removing From Sets

The remove() method removes a specified element from a set. If the element doesn’t exist within the set, the method raises an KeyError.

# Removing an element
my_set.remove(3)
print(my_set)  # Outputs: {1, 2, 4, 5}

When to Use Sets in Python

Sets are useful when you need to manage unique elements and perform set operations.

Removing Duplicates from a List

Use a set to remove duplicates from a list since sets do not allow duplicate values.

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)  # Outputs: [1, 2, 3, 4, 5]

Membership Testing

Sets are efficient for membership testing, allowing you to check if an item exists within a set.

fruits = {'apple', 'banana', 'cherry'}
print('apple' in fruits)  # Outputs: True
print('grape' in fruits)  # Outputs: False

Set Operations

Sets support mathematical operations like union, intersection, and difference, making them useful for comparing collections.

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union
print(set1 | set2)  # Outputs: {1, 2, 3, 4, 5}

# Intersection
print(set1 & set2)  # Outputs: {3}

# Difference
print(set1 - set2)  # Outputs: {1, 2}

Examples of Using Sets in Python

Filtering Unique Visitors

A web analytics platform might use a set to keep track of unique visitors to a website.

visitors = {'user1', 'user2', 'user3'}
new_visitors = {'user2', 'user3', 'user4'}

all_visitors = visitors | new_visitors
print(all_visitors)  # Outputs: {'user1', 'user2', 'user3', 'user4'}

Handling Tags in Social Media Posts

Social media platforms can use sets to manage unique tags in posts.

post_tags = {'python', 'coding', 'tutorial'}
new_tags = {'tutorial', 'programming', 'learning'}

all_tags = post_tags | new_tags
print(all_tags)  # Outputs: {'python', 'coding', 'tutorial', 'programming', 'learning'}

Managing Environment Variables

In Python, you can use sets to handle environment variables, ensuring each variable is unique.

import os

env_vars = set(os.environ.keys())
print(env_vars)  # Outputs: a set of environment variable names

Learn More About Python Sets

Python Set Methods

Python provides several methods for working with sets, including add(), remove(), discard(), pop(), clear(), and update().

my_set = {1, 2, 3}
my_set.add(4)  # Adds an element
my_set.remove(2)  # Removes an element
print(my_set)  # Outputs: {1, 3, 4}

Python Set Operations

Sets support various operations like union (|), intersection (&), difference (-), and symmetric difference (^).

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Symmetric Difference
print(set1 ^ set2)  # Outputs: {1, 2, 4, 5}

Python Set of Sets

Python does not allow sets of sets directly because sets are unhashable. However, you can create sets of frozensets, which are immutable.

set_of_sets = {frozenset({1, 2}), frozenset({3, 4})}
print(set_of_sets)  # Outputs: {frozenset({1, 2}), frozenset({3, 4})}

Python Ordered Set

Python's built-in set type is unordered. To maintain order, you can use collections.OrderedDict or the ordered-set library.

from collections import OrderedDict

ordered_set = list(OrderedDict.fromkeys([1, 2, 2, 3, 4]))
print(ordered_set)  # Outputs: [1, 2, 3, 4]

Converting Between Sets and Lists

You can convert a Python set into a list using the list() function. Similarly, you can convert a list into a set with the Python set() function. When a list contains duplicate elements, converting it to a set removes the duplicates.

# Converting set to list
my_set = {1, 2, 3}
my_list = list(my_set)
print(my_list)  # Outputs: [1, 2, 3]

# Converting list to set
my_list = [1, 2, 3, 3, 4]
my_set = set(my_list)
print(my_set)  # Outputs: {1, 2, 3, 4}

Python Set Differences

You can use the difference() method and the - operator to find the difference between two sets. The difference of two sets A and B (A - B) is the set of elements that are in A but not in B.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Using difference() method
diff1 = set1.difference(set2)
print(diff1)  # Outputs: {1, 2}

# Using - operator
diff2 = set1 - set2
print(diff2)  # Outputs: {1, 2}

With the difference_update() method, you can remove elements from a set that also exist within another set.

pythonCopy code
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

set1.difference_update(set2)
print(set1)  # Outputs: {1, 2}
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH