Python set methods
Created By: chatGPT
Sets in Python are a built-in data type used to store unordered collections of unique items. Here are some common methods associated with sets:
Creating a Set: You can create a set using curly braces or the
set()
function.my_set = {1, 2, 3}
another_set = set([1, 2, 3])
Add an Element: Use the
add()
method to add a single element to a set.my_set.add(4) # my_set is now {1, 2, 3, 4}
Update the Set: Use the
update()
method to add multiple elements from another set or list.my_set.update([5, 6]) # my_set is now {1, 2, 3, 4, 5, 6}
Remove an Element: Use the
remove()
method to remove a specific element. This raises an error if the element is not found.my_set.remove(3) # my_set is now {1, 2, 4, 5, 6}
Discard an Element: Similar to
remove()
, but does not raise an error if the element is not found.my_set.discard(10) # No error is raised and my_set remains unchanged.
Pop an Element: The
pop()
method removes and returns an arbitrary element from the set. The behavior is undefined if the set is empty.element = my_set.pop() # Removes and returns an arbitrary element
Clearing a Set: The
clear()
method removes all elements from the set.my_set.clear() # my_set is now an empty set
Set Length: Use the
len()
function to find out how many items are in a set.length = len(my_set) # Returns the number of elements in my_set
Set Mathematical Operations: Sets support mathematical operations like union, intersection, and difference.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union = set_a | set_b # {1, 2, 3, 4, 5}
intersection = set_a & set_b # {3}
difference = set_a - set_b # {1, 2}
Membership Testing: Check if an element is in a set using the
in
keyword.is_present = 2 in set_a # Returns True