A set in Python is an unordered collection of unique elements. It is similar to a list, but it does not allow duplicate values. Sets are useful when you need to store multiple values without caring about the order and without allowing duplicates.
A set is created by placing elements inside curly braces, or by using the set()
function.
# Creating a Set fruits = {"apple", "banana", "cherry"} print(fruits) # Output: {'apple', 'banana', 'cherry'}
- A set is unordered, meaning the elements have no defined order. - A set does not allow duplicate elements. If you try to add a duplicate element, it will be ignored. - Sets are mutable, meaning you can add or remove elements.
You can add elements to a set using the add()
method.
# Adding Elements to a Set fruits = {"apple", "banana", "cherry"} fruits.add("orange") print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}
You can remove elements from a set using the remove()
or discard()
methods.
- remove()
: Removes an element from the set, but raises a KeyError
if the element is not found.
- discard()
: Removes an element from the set, but does not raise an error if the element is not found.
# Removing Elements from a Set fruits = {"apple", "banana", "cherry", "orange"} fruits.remove("banana") # Removes 'banana' print(fruits) # Output: {'apple', 'cherry', 'orange'} # Discarding an Element fruits.discard("mango") # Does not raise an error if 'mango' is not present
Python sets support several operations like union, intersection, difference, and symmetric difference.
# Union of Sets set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1 | set2 # or set1.union(set2) print(union_set) # Output: {1, 2, 3, 4, 5}
# Intersection of Sets set1 = {1, 2, 3} set2 = {3, 4, 5} intersection_set = set1 & set2 # or set1.intersection(set2) print(intersection_set) # Output: {3}
# Difference of Sets set1 = {1, 2, 3} set2 = {3, 4, 5} difference_set = set1 - set2 # or set1.difference(set2) print(difference_set) # Output: {1, 2}
# Symmetric Difference of Sets set1 = {1, 2, 3} set2 = {3, 4, 5} symmetric_diff_set = set1 ^ set2 # or set1.symmetric_difference(set2) print(symmetric_diff_set) # Output: {1, 2, 4, 5}
You can check if an element exists in a set using the in
keyword.
# Set Membership fruits = {"apple", "banana", "cherry"} print("banana" in fruits) # Output: True print("orange" in fruits) # Output: False
You can find the length of a set using the len()
function.
# Set Length fruits = {"apple", "banana", "cherry"} print(len(fruits)) # Output: 3
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!