A set in Python is a collection of unique and unordered elements. Each element in a set must be unique, and the order of the elements does not matter. Sets are mutable, which means that you can add, remove, or modify elements after the set has been created.
Creating a Set
You can create a set in Python by enclosing a comma-separated list of elements within curly braces, like this:
my_set = {1, 2, 3, 4, 5}
Alternatively, you can use the set() function to create a set from a list or tuple, like this:
my_list = [1, 2, 3, 4, 5] my_set = set(my_list)
Python – Set Methods
1. Adding Elements: You can add elements to a set using the add() method, like this:
my_set.add(6)
2. Removing Elements: You can remove elements from a set using the remove() method, like this:
my_set.remove(5)
3. Checking Membership: You can check if an element is a member of a set using the in operator, like this:
if 4 in my_set: print("4 is in the set")
4. Set Operations: You can perform various set operations on sets, such as union, intersection, and difference, using built-in methods like union(), intersection(), and difference(), respectively.
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) intersection_set = set1.intersection(set2) difference_set = set1.difference(set2)