Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- """
- # Creating a set
- my_set = {1, 2, 3, 4, 5}
- # Creating an empty set
- empty_set = set()
- # Adding elements
- my_set.add(6) # Add a single element to the set
- my_set.update([7, 8, 9]) # Add multiple elements to the set
- # Removing elements
- my_set.remove(3) # Remove an element from the set, raises KeyError if not found
- my_set.discard(10) # Remove an element if it is a member, does nothing if not found
- removed_element = my_set.pop() # Remove and return an arbitrary element, raises KeyError if empty
- # Checking for elements
- is_in_set = 5 in my_set # Check if an element is in the set
- is_not_in_set = 10 not in my_set # Check if an element is not in the set
- # Set operations
- another_set = {4, 5, 6, 7}
- # Union
- union_set = my_set | another_set # Union of two sets
- union_set_method = my_set.union(another_set) # Union using the union() method
- # Intersection
- intersection_set = my_set & another_set # Intersection of two sets
- intersection_set_method = my_set.intersection(another_set) # Intersection using the intersection() method
- # Difference
- difference_set = my_set - another_set # Difference of two sets
- difference_set_method = my_set.difference(another_set) # Difference using the difference() method
- # Symmetric Difference
- sym_diff_set = my_set ^ another_set # Symmetric difference of two sets
- sym_diff_set_method = my_set.symmetric_difference(another_set) # Symmetric difference using the symmetric_difference() method
- # Checking subsets and supersets
- is_subset = {1, 2, 3}.issubset(my_set) # Check if a set is a subset
- is_superset = my_set.issuperset({1, 2, 3}) # Check if a set is a superset
- # Iterating through a set
- for element in my_set:
- print(element) # Print each element in the set
- # Set comprehensions
- squared_set = {x**2 for x in my_set} # Create a new set with squares of elements
- # Clearing a set
- my_set.clear() # Remove all elements from the set
- # Copying a set
- copied_set = another_set.copy() # Create a shallow copy of the set
Advertisement
Add Comment
Please, Sign In to add comment