Introduction to Python Sets
Python Sets
A set is an unordered collection of unique elements.
Sets are defined by enclosing the elements in curly braces {}
or by using the set()
constructor.
Sets can only contain immutable elements such as numbers, strings, or tuples, but not lists or other sets.
Here's an example of a set in Python:
fruits = {"apple", "banana", "orange"}
Creating a Set
You can create a set by enclosing elements in curly braces or by using the set()
constructor.
fruits = {"apple", "banana", "orange"}
numbers = set([1, 2, 3, 4, 5])
Set Operations
Sets support various operations such as union, intersection, difference, and symmetric difference.
Union (|):
Returns a new set that contains all unique elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set)
Intersection (&):
Returns a new set that contains elements present in both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2
print(intersection_set)
Difference (-):
Returns a new set that contains elements present in the first set but not in the second set.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2
print(difference_set)
Symmetric Difference (^):
Returns a new set that contains elements present in either set, but not both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set)
Set Methods
Sets have several built-in methods that you can use, such as add()
, remove()
, discard()
, pop()
, clear()
, copy()
, and more.
fruits = {"apple", "banana", "orange"}
fruits.add("kiwi")
print(fruits)
fruits.remove("banana")
print(fruits)
fruits.discard("kiwi")
print(fruits)
fruits.clear()
print(fruits)
Checking Set Membership
You can check if an element exists in a set using the in
operator. It returns True
if the element is found in the set and False
otherwise.
fruits = {"apple", "banana", "orange"}
print("banana" in fruits)
print("kiwi" in fruits)