Python Sets
⏱ Estimated reading time: 2 min
Python Sets
A set in Python is an unordered collection of unique items. Sets are mutable, but they do not allow duplicate elements. Sets are commonly used for membership testing, removing duplicates, and mathematical operations like union and intersection.
Creating a set:
Example:
my_set = {1, 2, 3, 4}
fruits = {"apple", "banana", "cherry"}
Empty set:
Use the set() function to create an empty set ({} creates a dictionary).
Example:
empty_set = set()
Accessing elements:
Sets are unordered, so you cannot access items by index. You can iterate through them using a loop.
Example:
for fruit in fruits:
print(fruit)
Adding elements:
-
add(): adds a single element
Example:
fruits.add("orange") -
update(): adds multiple elements
Example:
fruits.update(["kiwi", "mango"])
Removing elements:
-
remove(): removes an element; raises an error if not found
Example:
fruits.remove("apple") -
discard(): removes an element; does not raise an error if not found
Example:
fruits.discard("banana") -
pop(): removes and returns a random element
-
clear(): removes all elements
Set operations:
-
union(): combines two sets
Example:
a = {1,2,3}
b = {3,4,5}
print(a.union(b)) # {1,2,3,4,5} -
intersection(): returns common elements
print(a.intersection(b)) # {3} -
difference(): elements in one set but not in another
print(a.difference(b)) # {1,2} -
symmetric_difference(): elements in either set, but not both
print(a.symmetric_difference(b)) # {1,2,4,5}
Checking membership:
Use in and not in to check if an element exists.
Example:
if "apple" in fruits:
print("Found")
Immutable sets (frozenset):
Use frozenset() to create an immutable set that cannot be changed.
Example:
frozen = frozenset([1, 2, 3])
Register Now
Share this Post
← Back to Tutorials