Python sets

Created By: chatGPT

Sets in Python are unordered collections of unique elements. They are defined using curly braces {} or the set() function. Sets are particularly useful when you need to ensure that no duplicate values are present in your collection. Here’s how you can create and use sets in Python.
my_set = {1, 2, 3, 4}

# Creating a set using the set() function
another_set = set([4, 5, 6])
You can add elements to a set using the add() method. If you attempt to add an element that already exists in the set, it will not be added again.
my_set.add(5)
print(my_set)  # Output: {1, 2, 3, 4, 5}

my_set.add(3)
print(my_set)  # Output: {1, 2, 3, 4, 5}
To remove elements, you can use the remove() method or the discard() method. The difference is that remove() will raise an error if the element is not found, while discard() will not.
my_set.remove(4)
print(my_set)  # Output: {1, 2, 3, 5}

my_set.discard(7)  # No error raised
To find the intersection, union, or difference between sets, you can use operators like &, |, and -, or methods like intersection(), union(), and difference(). This is very handy when dealing with multiple collections.
set_a = {1, 2, 3}
set_b = {3, 4, 5}

# Intersection
intersection = set_a & set_b
print(intersection)  # Output: {3}

# Union
union = set_a | set_b
print(union)  # Output: {1, 2, 3, 4, 5}
Additionally, sets are highly performant for membership testing. Checking if an item is in a set is generally faster than checking in a list due to their underlying data structure.
if 2 in my_set:
    print('2 is in the set')
else:
    print('2 is not in the set')
Keep in mind that sets are mutable, meaning you can change them after creation, but they can only contain immutable elements (like strings, numbers, and tuples).
immutable_set = {1, 2, (3, 4)}  # This is valid
# immutable_set.add([5])  # This would raise an error
Introduction And SetupVariablesData TypesIntFloatStrBoolListTupleSetDictMethodsString MethodsList MethodsDict MethodsSet MethodsControl FlowIf StatementElif StatementElse StatementFor LoopWhile LoopBreak StatementContinue StatementFunctionsDef StatementReturn StatementLambda FunctionsScopeParametersArgumentsDefault ParametersVariable Length ArgumentsOperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsAssignment OperatorsIdentity OperatorsMembership OperatorsData StructuresListsTuplesSetsDictionariesCommentsSingle Line CommentsMulti Line CommentsSyntaxIndentationDocstringsEvent HandlingError HandlingTry StatementExcept StatementFinally StatementRaise StatementAssert StatementContext ManagersWith Statement