Python Set Creation and Operations
In Python, a set is an unordered and mutable data type used to store a collection of unique elements. A set can contain any immutable data types, such as numbers, strings, and tuples. Unlike lists and tuples, sets do not have order; therefore, they cannot be accessed using indices like lists or tuples allow.
Creating a set is straightforward: simply use a pair of curly braces {} or the set() function to place elements within the braces, separated by commas. For example:
my_set = {1, 2, 3, 4, 5}
# Alternatively, using the set() function
my_set = set([1, 2, 3, 4, 5])
When creating a set, duplicate elements are automatically removed because sets can only contain unique elements. Sets support many basic operations, such as adding elements, removing elements, and checking for element existence. Here are some examples of set operations:
# Create a set
my_set = {1, 2, 3, 4, 5}
# Add an element
my_set.add(6)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
# Remove an element
my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5, 6}
# Check for element existence
print(4 in my_set) # Output: True
print(3 in my_set) # Output: False
Additionally, sets support mathematical set operations such as unions, intersections, and differences. For example:
# Create two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union operation
print(set1 | set2) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
# Intersection operation
print(set1 & set2) # Output: {4, 5}
# Difference operation
print(set1 - set2) # Output: {1, 2, 3}