← Back to all snippets
PYTHON

Efficiently Find Common and Unique Elements Using Python Sets

Leverage Python's set data structure for quick operations like finding common elements (intersection) and unique elements (difference) between two lists or collections.

list1 = [1, 2, 3, 4, 5, 5, 6]
list2 = [4, 5, 6, 7, 8, 8, 9]

set1 = set(list1)
set2 = set(list2)

# Common elements
common_elements = set1.intersection(set2)
print(f"Common elements: {common_elements}")

# Elements unique to list1
unique_to_list1 = set1.difference(set2)
print(f"Unique to list1: {unique_to_list1}")

# Elements unique to list2
unique_to_list2 = set2.difference(set1)
print(f"Unique to list2: {unique_to_list2}")

# All unique elements from both lists (union)
all_unique_elements = set1.union(set2)
print(f"All unique elements: {all_unique_elements}")

# Check for subsets
is_subset = {1, 2}.issubset(set1)
print(f"Is {{1, 2}} a subset of set1? {is_subset}")
How it works: This snippet demonstrates the power of Python's `set` data structure for performing efficient operations such as finding common elements, elements unique to one set, and combining all unique elements. Sets automatically handle uniqueness and provide optimized methods like `intersection()`, `difference()`, `union()`, and `issubset()` for quick comparisons and manipulations of collections. This is highly useful for data cleaning, comparison, and analysis tasks in web applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs