In Python, a set is another commonly used data structure that allows you to store and manipulate collections of data. A set is an unordered collection of unique elements, which can be of any data type.
Here is an example of creating and working with a set in Python:
python # Create a set my_set = {1, 2, 3, "four", 5.0} # Add an element to the set my_set.add(6) # Remove an element from the set my_set.remove("four") # Iterate over the elements of the set for item in my_set: print(item)
In this example, a set called `my_set` is created with five elements of different data types. The `add()` method is used to add an element to the set, and the `remove()` method is used to remove the element `”four”` from the set. Finally, a `for` loop is used to iterate over the elements of the set and output them to the console.
Sets in Python are useful for situations where you need to keep track of a collection of unique elements. They can also be used to perform set operations, such as union, intersection, and difference. Here is an example:
python # Create two sets set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} # Perform set operations union = set1.union(set2) intersection = set1.intersection(set2) difference = set1.difference(set2) # Output the results print(union) # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(intersection) # Output: {4, 5} print(difference) # Output: {1, 2, 3}
In this example, two sets (`set1` and `set2`) are created, and then union, intersection, and difference operations are performed on them using the `union()`, `intersection()`, and `difference()` methods. The resulting sets (`union`, `intersection`, and `difference`) contain the elements that are in both sets, only in the first set, and only in the second set, respectively.
Sets are a useful data structure in Python and are used in a wide variety of applications, such as filtering out duplicates from a collection of data or performing set operations on data sets.