Skip to content

Python Sets

Python sets are unordered collections of unique elements. Sets are mutable, meaning that you can add or remove elements from a set after it has been created. One of the defining features of sets is that they only contain unique elements, which makes them a useful tool for data manipulation and analysis.

Creating Sets

To create a set in Python, you can use the set() function or curly braces {}. Here's an example of creating a set using the set() function:

Convert a list to a set in Python

python
my_set = set([1, 2, 3])
print(my_set) # {1, 2, 3}

You can also create a set using curly braces:

Define a set in Python

python
my_set = {1, 2, 3}
print(my_set) # {1, 2, 3}

Adding and Removing Elements

To add an element to a set, you can use the add() method:

Add an element to a set in Python

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

To remove an element from a set, you can use the remove() or discard() methods:

Remove an element from a set in Python

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

my_set.discard(3)
print(my_set) # {1, 2}

Set Operations

Sets support various set operations, such as union, intersection, and difference. Here are some examples:

Set operations in Python

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

# Union
print(set1.union(set2)) # {1, 2, 3, 4}

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

# Difference
print(set1.difference(set2)) # {1}

Practical Examples

Sets can be used in many practical applications. For example, you can use sets to remove duplicates from a list:

Remove duplicates from a list using a set in Python

python
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(my_list)
unique_list = list(unique_set)
print(unique_list) # [1, 2, 3, 4, 5]

You can also use sets to check if two lists have any elements in common:

Check if two lists have any elements in common in Python using sets

python
list1 = [1, 2, 3]
list2 = [3, 4, 5]

set1 = set(list1)
set2 = set(list2)

if set1.intersection(set2):
    print("The two lists have at least one common element.")
else:
    print("The two lists do not have any common elements.")

Conclusion

In this article, we've covered the basics of Python sets, including how to create sets, add and remove elements, perform set operations, and use sets in practical applications. With this knowledge, you can start incorporating sets into your Python code to manipulate and analyze data more effectively. We hope you found this guide helpful!

Practice

What are the characteristics and features of a Python set?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.