Set Python
Set Python
,
the first set contains all elements of the second).
• Unordered: The order of elements is not guaranteed and can vary.
12. pop(): Removes and returns an arbitrary element from the set. Sets are
• Unchangeable: While the set itself is mutable (i.e., you can add/remove unordered, so the element removed is unpredictable.
elements), individual elements cannot be modified.
13. remove(): Removes the specified element from the set. Raises a KeyError
• Duplicates: Sets automatically discard duplicate values. if the element is not found.
1. add(): Adds an element to the set. If the element is already present, it 14. symmetric_difference() (^): Returns a set containing elements that are in
won't add it again (sets automatically handle uniqueness). either of the sets, but not in both.
2. clear(): Removes all elements from the set, leaving it empty. 15. symmetric_difference_update() (^=): Modifies the set to include only
elements that are in either set, but not in both.
3. copy(): Returns a shallow copy of the set. Modifications to the copy do
not affect the original set. 16. union() (|): Returns a new set containing all elements from both sets,
excluding duplicates.
4. difference() (-): Returns the set difference (elements present in the first
set but not in the second). 17. update() (|=): Modifies the set by adding elements from one or more
other sets.
5. difference_update() (-=): Modifies the set to remove elements that are
present in another set. 18. len(): Returns the number of elements in the set.
6. discard(): Removes the specified element if present, but does nothing if 19. set() constructor: Can be used to create a new set from an iterable (like a
the element is absent (unlike remove() which raises an error). list or string).
7. intersection() (&): Returns the intersection (common elements) between 20. del: Completely deletes a set.
two or more sets.
Additionally:
8. intersection_update() (&=): Modifies the set to only contain elements
that are also in another set. you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
9. isdisjoint(): Returns True if two sets have no elements in common (i.e.,
if element in my_set:
they are disjoint), otherwise returns False.
print("Element is in the set")
10. issubset() (<=): Returns True if the set is a subset of another set (i.e., all
elements in the first set are also in the second). The values True and 1 or False and 0 are considered the same value in sets, and
are treated as duplicates