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 setmy_set = set() # Creating a set with elementsmy_set = {1, 2, 3} # Creating a set using the set() functionmy_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 setmy_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 setmy_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 setsA = {1, 2, 3}B = {3, 4, 5} # Unionprint(A.union(B)) # Output: {1, 2, 3, 4, 5} # Intersectionprint(A.intersection(B)) # Output: {3} # Differenceprint(A.difference(B)) # Output: {1, 2} # Symmetric Differenceprint(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 Bprint(A.issubset(B)) # Output: True # Check if B is a superset of Aprint(B.issuperset(A)) # Output: True # Check if C is a subset of Aprint(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