Sets are unordered collections of unique elements. They are particularly useful when you need to store a collection of distinct items and perform set operations like union, intersection, difference, and so on. Here's an overview of Python sets:
You can create a set by enclosing elements within curly braces `{}`.
my_set = {1, 2, 3, 4, 5}
Alternatively, you can use the `set()` function to create a set from an iterable (like a list or tuple).
my_set = set([1, 2, 3, 4, 5])
Sets contain only unique elements. If you try to add duplicate elements, they will be ignored.
my_set = {1, 2, 3, 4, 5, 1} # Duplicate 1 will be ignored
print(my_set) # Output: {1, 2, 3, 4, 5}
Since sets are unordered, they do not support indexing or slicing like lists or tuples. You can, however, check for membership using the `in` operator.
print(3 in my_set) # Output: True
Sets support various mathematical set operations such as union, intersection, difference, and symmetric difference.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
intersection_set = set1 & set2
difference_set = set1 - set2
symmetric_difference_set = set1 ^ set2
print(union_set) # Output: {1, 2, 3, 4, 5}
print(intersection_set) # Output: {3}
print(difference_set) # Output: {1, 2}
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
Sets have various built-in methods for performing common operations like adding elements, removing elements, and checking subsets.
Python also has another type of set called frozen sets. Frozen sets are immutable and can be created using the frozenset() function.
frozen_set = frozenset([1, 2, 3])
Frozen sets support all set methods that don't modify the set (e.g., union(), intersection(), difference(), etc.).
Sets are a powerful tool for various operations involving collections of unique elements.