Sitemap
Python Journal

Learn with Python Devs.

Member-only story

Master Python Sets: Tips, Tricks, and Best Practices

2 min readAug 28, 2024

--

Press enter or click to view image in full size

What is set in Python?

Set: A Python set is an unordered collection of unique elements.

_set = {"apple"}
_set = set()
_not_set = {}

Removing element:

fruits = {"apple", "banana", "cherry"}
fruits.discard("banana") # discard() will not raise an error.
fruits.remove("banana") # Raises KeyError if "banana" is not in the set
print(fruits) # Output: {'apple', 'cherry'}

Removing Duplicates from a List using a Set:

fruits = ["apple", "banana", "cherry", "apple", "banana", "cherry", "kiwi"]
unique_items = list(set(fruits)) # Output: ["apple", "banana", "cherry", "kiwi"]

Set operations:

0. Joining two sets:

set1 = {"apple", "banana", "cherry"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1) # Output: {1, 2, 3, 'b', 'c', 'a'}

# Or
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 'b', 'c', 'a'}
  1. Common elements between two sets:

--

--

Tushar Bosamiya
Tushar Bosamiya

Written by Tushar Bosamiya

Self-taught Dev. sharing insights on software development, Python, Data Engineering, AWS, GCP and Azure. Follow for innovative and valuable software insights!