Sets are an essential data structure in Python used to store unique elements. Unlike lists or tuples, sets do not allow duplicate values. In this topic, we'll explore everything you need to know about sets, from basic operations to advanced techniques.
A set is an unordered collection of unique elements enclosed within curly braces {}
.
To create a set in Python, you can use curly braces {}
or the set()
function.
# Example of creating a set
my_set = {1, 2, 3, 4, 5}
Since sets are unordered, you cannot access elements by index. However, you can iterate over the elements of a set using a loop.
# Example of iterating over a set
for item in my_set:
print(item)
You can add elements to a set using the add()
method.
# Example of adding elements to a set
my_set.add(6)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
You can remove elements from a set using methods like remove()
or discard()
.
# Example of removing elements from a set
my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5}
my_set.discard(2)
print(my_set) # Output: {1, 4, 5}
Sets support various mathematical operations like union, intersection, difference, and symmetric difference.
# Example of set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
# Intersection
intersection_set = set1 & set2
print(intersection_set) # Output: {4, 5}
# Difference
difference_set = set1 - set2
print(difference_set) # Output: {1, 2, 3}
# Symmetric Difference
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # Output: {1, 2, 3, 6, 7, 8}
Set comprehensions provide a concise way to create sets based on existing iterables.
# Example of set comprehension
squared_numbers = {x ** 2 for x in range(1, 6)}
print(squared_numbers) # Output: {1, 4, 9, 16, 25}
Frozen sets are immutable sets, meaning their elements cannot be changed after creation.
# Example of frozen set
my_frozen_set = frozenset({1, 2, 3, 4, 5})
Sets are powerful data structures in Python used to store unique elements efficiently. By understanding the basics of sets, including creation, accessing elements, and common operations like adding, removing, and set operations, you can effectively work with unique collections of data in your Python programs. Additionally, exploring advanced techniques like set comprehensions and frozen sets enhances your ability to manipulate sets in various scenarios. Remember to leverage sets where uniqueness is desired and practice using them to solve problems and optimize your code. Happy Coding!❤️