Wednesday, 11 January 2023

Python Sets

 

In Python, a set is a collection of unique elements. Sets are used to store multiple items in a single variable. Sets are defined by curly braces {} or the set() function. Elements in a set are not ordered, so they can not be accessed by index.

Here is an example of how to create a set in Python:

# Creating an empty set
my_set = set()
 
# Creating a set with elements
my_set = {1, 2, 3}
 
# Creating a set using the set() function
my_set = set([1, 2, 3])

You can add elements to a set using the add() method. Here is an example:

my_set = {1, 2, 3}
 
# Adding an element to the set
my_set.add(4)
 
print(my_set) # Output: {1, 2, 3, 4}

You can remove elements from a set using the discard() or remove() method. The difference between the two is that remove() raises an error if the element is not found in the set, while discard() does not.

my_set = {1, 2, 3, 4}
 
# Removing an element from the set
my_set.discard(3)
 
print(my_set) # Output: {1, 2, 4}

You can also perform mathematical operations on sets such as union, intersection, difference, and symmetric difference. Here is an example:

# Defining two sets
A = {1, 2, 3}
B = {3, 4, 5}
 
# Union
print(A.union(B)) # Output: {1, 2, 3, 4, 5}
 
# Intersection
print(A.intersection(B)) # Output: {3}
 
# Difference
print(A.difference(B)) # Output: {1, 2}
 
# Symmetric Difference
print(A.symmetric_difference(B)) # Output: {1, 2, 4, 5}

You can also check if a set is a subset or superset of another set, here is an example:

A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {1, 2}
 
# Check if A is a subset of B
print(A.issubset(B)) # Output: True
 
# Check if B is a superset of A
print(B.issuperset(A)) # Output: True
 
# Check if C is a subset of A
print(C.issubset(A)) # Output: True

Sets are a powerful tool for storing and manipulating unique elements in Python. They are efficient and versatile, making them a popular choice for many use cases such as data manipulation and cleaning.


Amelioration

This article was researched and written with the help of ChatGPT, a language model developed by OpenAI."

 "Special thanks to ChatGPT for providing valuable information and examples used in this article."

 

No comments:

Post a Comment