nathanwailes

Sets

Jun 9th, 2024
427
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. """
  2. """
  3. # Creating a set
  4. my_set = {1, 2, 3, 4, 5}
  5.  
  6. # Creating an empty set
  7. empty_set = set()
  8.  
  9. # Adding elements
  10. my_set.add(6)                   # Add a single element to the set
  11. my_set.update([7, 8, 9])        # Add multiple elements to the set
  12.  
  13. # Removing elements
  14. my_set.remove(3)                # Remove an element from the set, raises KeyError if not found
  15. my_set.discard(10)              # Remove an element if it is a member, does nothing if not found
  16. removed_element = my_set.pop()  # Remove and return an arbitrary element, raises KeyError if empty
  17.  
  18. # Checking for elements
  19. is_in_set = 5 in my_set         # Check if an element is in the set
  20. is_not_in_set = 10 not in my_set  # Check if an element is not in the set
  21.  
  22. # Set operations
  23. another_set = {4, 5, 6, 7}
  24.  
  25. # Union
  26. union_set = my_set | another_set                # Union of two sets
  27. union_set_method = my_set.union(another_set)    # Union using the union() method
  28.  
  29. # Intersection
  30. intersection_set = my_set & another_set         # Intersection of two sets
  31. intersection_set_method = my_set.intersection(another_set)  # Intersection using the intersection() method
  32.  
  33. # Difference
  34. difference_set = my_set - another_set           # Difference of two sets
  35. difference_set_method = my_set.difference(another_set)  # Difference using the difference() method
  36.  
  37. # Symmetric Difference
  38. sym_diff_set = my_set ^ another_set             # Symmetric difference of two sets
  39. sym_diff_set_method = my_set.symmetric_difference(another_set)  # Symmetric difference using the symmetric_difference() method
  40.  
  41. # Checking subsets and supersets
  42. is_subset = {1, 2, 3}.issubset(my_set)          # Check if a set is a subset
  43. is_superset = my_set.issuperset({1, 2, 3})      # Check if a set is a superset
  44.  
  45. # Iterating through a set
  46. for element in my_set:
  47.     print(element)                              # Print each element in the set
  48.  
  49. # Set comprehensions
  50. squared_set = {x**2 for x in my_set}            # Create a new set with squares of elements
  51.  
  52. # Clearing a set
  53. my_set.clear()                                  # Remove all elements from the set
  54.  
  55. # Copying a set
  56. copied_set = another_set.copy()                 # Create a shallow copy of the set
  57.  
Advertisement
Add Comment
Please, Sign In to add comment