Python Set Operations: How to Use union, intersection, and difference

Python’s set type does not just store unique elements; it also provides powerful methods for Set Operations (Logical Operations), just like in mathematics.

  • Union: All elements from both sets (no duplicates).
  • Intersection: Elements common to both sets.
  • Difference: Elements present in one set but not the other.

These operations are useful in many scenarios, such as data analysis, permission management, and handling duplicates. This article explains the major set operation methods.


目次

Preparation: Sample Sets

As an example, we will define permissions for two different user groups using sets.

# Permissions for Editor Group
editors_permissions = {"read", "write", "comment"}

# Permissions for Admin Group
admins_permissions = {"comment", "delete", "admin_access", "write"}

print(f"Editors: {editors_permissions}")
print(f"Admins: {admins_permissions}")

Output:

Editors: {'comment', 'read', 'write'}
Admins: {'write', 'delete', 'comment', 'admin_access'}

(Since sets are unordered, the display order may vary.)


1. Union: .union() or |

The Union creates a new set containing all unique elements from both sets. Use this to get all types of permissions held by either Editors or Admins.

# Using the .union() method
all_permissions = editors_permissions.union(admins_permissions)
print(f"All Permissions (union): {all_permissions}")

# The | (pipe) operator gives the same result
all_permissions_op = editors_permissions | admins_permissions
print(f"All Permissions (|): {all_permissions_op}")

Output:

All Permissions (union): {'comment', 'admin_access', 'read', 'delete', 'write'}
All Permissions (|): {'comment', 'admin_access', 'read', 'delete', 'write'}

2. Intersection: .intersection() or &

The Intersection creates a new set containing only elements that exist in both sets. Use this to find permissions shared by both Editors and Admins.

# Using the .intersection() method
common_permissions = editors_permissions.intersection(admins_permissions)
print(f"Common Permissions (intersection): {common_permissions}")

# The & (ampersand) operator gives the same result
common_permissions_op = editors_permissions & admins_permissions
print(f"Common Permissions (&): {common_permissions_op}")

Output:

Common Permissions (intersection): {'comment', 'write'}
Common Permissions (&): {'comment', 'write'}

3. Difference: .difference() or -

The Difference creates a new set containing elements that exist in the first set but not in the second set. Use this to find permissions that only Editors have (permissions not held by Admins).

# Using the .difference() method
editor_only_permissions = editors_permissions.difference(admins_permissions)
print(f"Editor Only (difference): {editor_only_permissions}")

# The - (hyphen) operator gives the same result
editor_only_permissions_op = editors_permissions - admins_permissions
print(f"Editor Only (-): {editor_only_permissions_op}")

# Reversing the order gives permissions unique to Admins
admin_only_permissions = admins_permissions.difference(editors_permissions)
print(f"Admin Only: {admin_only_permissions}")

Output:

Editor Only (difference): {'read'}
Editor Only (-): {'read'}
Admin Only: {'delete', 'admin_access'}

4. Subset and Superset

There are also methods to check if two sets have an inclusion relationship. These return a boolean value (True / False).

  • .issubset() or <=: Checks if Set A is a subset of Set B (all elements of A are in B).
  • .issuperset() or >=: Checks if Set A is a superset of Set B (A contains all elements of B).
# Other sample sets
basic_access = {"read"}
full_access = {"read", "write", "delete"}

# --- Subset ---
# Is "basic_access" a subset of "full_access"?
is_subset = basic_access.issubset(full_access)
print(f"is_subset: {is_subset}")

# Operator
print(f"<=: {basic_access <= full_access}")

# --- Superset ---
# Is "full_access" a superset of "basic_access"?
is_superset = full_access.issuperset(basic_access)
print(f"is_superset: {is_superset}")

# Operator
print(f">=: {full_access >= basic_access}")

Output:

is_subset: True
<=: True
is_superset: True
>=: True

Summary

Set operations are very powerful for extracting commonalities or differences between two groups.

  • Union (.union() or |): All elements.
  • Intersection (.intersection() or &): Common elements.
  • Difference (.difference() or -): Elements unique to one side.
  • Inclusion (.issubset(), .issuperset()): Checks relationship (True/False).

By using these methods and operators, you can write complex data comparison and filtering logic concisely.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次