PYTHON

Perform Efficient Set Operations and Find Unique Elements

Utilize Python's built-in `set` data type to quickly find unique items, calculate unions, intersections, and differences between collections for data cleaning and comparison.

# Creating sets
set1 = {'apple', 'banana', 'cherry', 'date'}
set2 = {'cherry', 'date', 'elderberry', 'fig'}
list_with_duplicates = ['apple', 'banana', 'apple', 'grape', 'banana']

# Finding unique elements from a list (order not preserved)
unique_elements = set(list_with_duplicates)
print(f"Unique elements: {unique_elements}")

# Union of sets (elements in either set)
union_set = set1.union(set2)
print(f"Union: {union_set}")

# Intersection of sets (elements common to both sets)
intersection_set = set1.intersection(set2)
print(f"Intersection: {intersection_set}")

# Difference (elements in set1 but not in set2)
difference_set = set1.difference(set2)
print(f"Difference (set1 - set2): {difference_set}")

# Symmetric difference (elements in either set, but not in both)
symmetric_difference_set = set1.symmetric_difference(set2)
print(f"Symmetric Difference: {symmetric_difference_set}")

# Checking for membership
print(f"'apple' in set1: {'apple' in set1}")
print(f"'grape' in set2: {'grape' in set2}")
How it works: Python's `set` is an unordered collection of unique elements. It's incredibly efficient for membership testing and performing standard mathematical set operations like union, intersection, difference, and symmetric difference. Converting a list to a set is the quickest way to get unique elements from it (though it won't preserve the original order). Sets are ideal for scenarios requiring fast lookups and comparisons between collections of items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs