Set methods

Operations that are specific to sets and frozensets generally provide a way to quickly compare and shift out common/uncommon items between the different sets. Examples of the following methods can be seen in the next screenshot. The following non-exhaustive listing of set methods is an example of the more common set methods.

However, be sure to review the official Python documentation as there are some differences between set and frozenset methods:

  • set1.isdisjoint(set2): Returns True if set1 has no elements in common with set2
  • set1.issubset(set2): Returns True if every element in set1 exists in set2
  • set1 < set2: Returns True if set1 is a true subset of set2 but not exactly equal to set2
  • set1.issuperset(set2): Returns True if every element in set2 is in set1
  • set1 > set2: Returns True if set1 is a true superset of set2 but not exactly equal to set2
  • set1.union(set2, set3, ...): Returns a new set that includes elements from all given sets
  • set1.intersection(set2, set3, ...): Returns a new set with all common elements between the given sets
  • set1.difference(set2, set3, ...): Returns a new set with elements that exists in set1 but are not in any others
  • set1.symmetric_difference(set2): Returns a new set with elements that are unique to each set
  • set1.copy(): Returns a new set with a copy of the elements from set1

The following screenshot shows an example of set method:

Set method examples

Lines 104 and 105 create two different sets. Lines 106-110 are self-explanatory, based on the previous definitions.

With line 111, we create a new set by merging set1 with set2. Line 112 shows a returned, empty set because there are no common elements between the two sets.

Line 113 shows the elements that exist in set1 but not set2, while line 114 shows all the unique elements.

Finally, line 115 presents a copy of set1; normally, this would be assigned to a new variable for later use.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset