SETS

Sets in Python are unordered collections of unique elements. Sets are defined using curly braces {} or the set() constructor. Sets do not allow duplicate elements, and they are mutable, meaning you can add or remove elements from them.

Creating a Set:

You can create a set by enclosing comma-separated values within curly braces {}.

my_set = {1, 2, 3, 4, 5}

Creating a Set from a List:

You can also create a set from a list using the set() constructor.

my_list = [1, 2, 3, 4, 5]
my_set = set(my_list)

Accessing Elements:

Since sets are unordered collections, they do not support indexing. However, you can check for membership using the in operator.

print(1 in my_set)  # Output: True

Adding and Removing Elements:

You can add elements to a set using the add() method, and remove elements using the remove() or discard() method.

my_set.add(6)
print(my_set)  # Output: {1, 2, 3, 4, 5, 6}

my_set.remove(3)
print(my_set)  # Output: {1, 2, 4, 5, 6}

Set Operations:

Sets support various mathematical operations, such as union, intersection, difference, and symmetric difference.

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union
print(set1 | set2)  # Output: {1, 2, 3, 4, 5}

# Intersection
print(set1 & set2)  # Output: {3}

# Difference
print(set1 - set2)  # Output: {1, 2}

# Symmetric Difference
print(set1 ^ set2)  # Output: {1, 2, 4, 5}

Sets are useful for various tasks such as removing duplicates from a list, performing mathematical operations, and checking for membership or uniqueness of elements.

Sure, here are some commonly used set methods in Python:

1. add(element):

Adds a single element to the set. If the element is already present, it does nothing.

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # Output: {1, 2, 3, 4}

2. update(iterable):

Adds multiple elements to the set from an iterable (such as another set, list, or tuple).

my_set = {1, 2, 3}
my_set.update([4, 5, 6])
print(my_set)  # Output: {1, 2, 3, 4, 5, 6}

3. remove(element):

Removes a specified element from the set. Raises a KeyError if the element is not present.

my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)  # Output: {1, 3}

4. discard(element):

Removes a specified element from the set if it is present. Does nothing if the element is not present.

my_set = {1, 2, 3}
my_set.discard(2)
print(my_set)  # Output: {1, 3}

5. pop():

Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty.

my_set = {1, 2, 3}
popped_element = my_set.pop()
print(popped_element)  # Output: 1
print(my_set)  # Output: {2, 3}

6. clear():

Removes all elements from the set, leaving it empty.

my_set = {1, 2, 3}
my_set.clear()
print(my_set)  # Output: set()

These are some of the commonly used methods for working with sets in Python. Sets offer efficient methods for adding, removing, and performing set operations, making them useful in various programming scenarios.