Sets

Python Sets are a collection data type that is unordered and unchangeable. They are used to store multiple items in a single variable. Unlike lists and tuples, sets have unique elements, which means that duplicates are not allowed.

Sets are defined using curly brackets {} or the set() method. For example:

# Creating a set using curly brackets
fruits = {'apple', 'banana', 'cherry'}
print(fruits) # Output: {'banana', 'cherry', 'apple'}

# Creating a set using the set() method
vegetables = set(['carrot', 'potato', 'onion'])
print(vegetables) # Output: {'carrot', 'onion', 'potato'}

Note that the order of the elements in the set may not be the same as the order in which they were added. This is because sets are unordered, meaning that the items have no index.

Sets are useful when you want to perform operations such as union, intersection, difference, and symmetric difference between two or more sets. These operations can be performed using the union(), intersection(), difference(), and symmetric_difference() methods, respectively.

For example, consider the following sets:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

The union of sets A and B would be the set of all elements that are in either A or B, or in both:

# Union of sets A and B
print(A.union(B)) # Output: {1, 2, 3, 4, 5, 6}

The intersection of sets A and B would be the set of all elements that are in both A and B:

# Intersection of sets A and B
print(A.intersection(B)) # Output: {3, 4}

The difference of sets A and B would be the set of all elements that are in A but not in B:

# Difference of sets A and B
print(A.difference(B)) # Output: {1, 2}

The symmetric difference of sets A and B would be the set of all elements that are in either A or B, but not in both:

# Symmetric difference of sets A and B
print(A.symmetric_difference(B)) # Output: {1, 2, 5, 6}

Sets also support mathematical operations such as union, intersection, difference, and symmetric difference. The union of two sets can be represented as A | B, the intersection of two sets as A & B, the difference of two sets as A – B, and the symmetric difference of two sets as A ^ B.

For example:

# Union of sets A and B using the pipe symbol
print(A | B) # Output: {1, 2, 3, 4, 5, 6}

# Intersection of sets A and B using the ampersand symbol
print(A & B) # Output: {3, 4}

# Difference of sets A and B using the minus symbol
print(A - B) # Output: {1, 2}

# Symmetric difference of sets A and B using the caret symbol
print(A ^ B) #