In Python, a set is a collection of unordered and unindexed items, all of which are unique. Sets in Python are a very useful and versatile data type that are often used for tasks such as eliminating duplicate entries from a list, performing mathematical operations such as intersection, union, and difference, or testing for membership. Sets are denoted by enclosing comma-separated items in curly brackets '{}'.
Key properties of Python sets are:
1. Unordered: Sets in Python are unordered collections, meaning that the elements don't have a specific order. The order in which elements are added to the set is not necessarily the order in which they are stored or retrieved.
2. Does Not Allows Duplicate Members: Sets in Python do not contain duplicate elements. That is, each value can appear at most once in a set. If you try to add a duplicate element to a set, it simply ignores the action and leaves the set unchanged.
3. Unindexed: Sets are unindexed, which means you cannot access items in a set by referring to an index.
4. Mutable: Although you cannot change or replace items of a set, you can add new items to it or remove items from it.
Creating Sets:
To create a set in Python, you simply enclose the elements you want to include within curly brackets '{}', separated by commas.
# Examples of creating sets
numbers = {1, 2, 3, 4, 5} # A set of integers
names = {"Alice", "Bob", "Charlie"} # A set of strings
mixed = {1, "Alice", True} # A set with mixed data types
Using set() Constructor:
Python also provides the 'set()' constructor, which you can use to create a set from an existing iterable object such as a string, list, tuple, or another set.
# Using set() constructor with a string
str_set = set("Hello")
print(str_set) # Outputs: {'e', 'o', 'H', 'l'}
# Using set() constructor with a list
list_set = set([1, 2, 3, 4])
print(list_set) # Outputs: {1, 2, 3, 4}
Note that the 'set()' constructor creates a set without any elements when called without arguments.
empty_set = set()
print(empty_set) # Outputs: set()
Set Length:
In Python, the `len()` function is used to get the number of items (length) of a set.
Here is an example:
numbers = {1, 2, 3, 4, 5}
length = len(numbers)
print(length) # Outputs: 5
Check Items:
fruits = {"apple", "banana", "cherry"}
if "apple" in fruits:
print("Yes, 'apple' is in the fruits set") # This will be printed
Add Items:
fruits = {"apple", "banana", "cherry"}
fruits.add("date")
print(fruits) # Outputs: {'apple', 'date', 'banana', 'cherry'}
fruits = {"apple", "banana", "cherry"}
fruits.update({"date", "elderberry"})
print(fruits) # Outputs: {'elderberry', 'apple', 'date', 'banana', 'cherry'}
Remove Items:
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits) # Outputs: {'apple', 'cherry'}
# If you try to remove an item that does not exist, you will get a KeyError:
# fruits.remove("orange") # Raises KeyError: 'orange'
fruits = {"apple", "banana", "cherry"}
fruits.discard("cherry")
print(fruits) # Outputs: {'apple', 'banana'}
# You can discard an item that does not exist without getting an error:
fruits.discard("orange") # Does nothing
fruits = {"apple", "banana", "cherry"}
popped = fruits.pop()
print(popped) # Outputs an arbitrary item from the set
print(fruits) # Outputs the remaining set
# If the set is empty, you will get a KeyError:
# empty_set = set()
# empty_set.pop() # Raises KeyError: 'pop from an empty set'
fruits = { "apple", "banana", "cherry" }
fruits.clear()
print(fruits) # Outputs: set()
fruits = { "apple", "banana", "cherry" }
del fruits
# If you try to print the set after deleting it, you will get a NameError :
# print(fruits) # Raises NameError : name 'fruits' is not defined
Set Operations:
1. Union:
set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
result = set1.union(set2) # Using the union() method
print(result) # Outputs: {1, 2, 3, 4, 5}
set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
set1.update(set2) # Using the update() method
print(set1) # Outputs: {1, 2, 3, 4, 5}
2. Intersection:
set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
result = set1.intersection(set2) # Using the intersection() method
print(result) # Outputs: {3}
set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
set1.intersection_update(set2) # Using the intersection_update() method
print(set1) # Outputs: {3}
3. Symmetric Difference:
set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
result = set1.symmetric_difference(set2) # Using the symmetric_difference() method
print(result) # Outputs: {1, 2, 4, 5}
set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
set1.symmetric_difference_update(set2) # Using the symmetric_difference_update() method
print(set1) # Outputs: {1, 2, 4, 5}