set1 - ibrahimrifats/Back-End-development GitHub Wiki
Here's the topic about sets and the Python code written in a nice Markdown format:
Sets in Python
A set is an unordered collection of unique elements in Python. It is defined by enclosing elements within curly braces {}. Sets are useful for performing various operations such as union, intersection, difference, and symmetric difference.
Examples:
# Define two sets
set_a = {1, 3, 4, 54, 'string'}
set_b = {9, 8, 7, 7, 4, 5, 6, 6, 3, 2, 1}
# Perform set operations on set_a
set_a.remove('string') # Remove 'string' from set_a
set_a.add('rifat') # Add 'rifat' to set_a
set_a.discard(54) # Discard 54 from set_a (if present)
set_a.discard('rifat') # Discard 'rifat' from set_a (if present)
# Print the updated sets
print(set_a) # Output: {1, 3, 4, 'rifat'}
print(set_b) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}
# Define two more sets
set_d = {65, 45, 2, 7, 23, 7, 4}
set_e = {65, 34, 1, 74, 23, 'fag'}
# Set operations on set_d and set_e
print('Union:', set_d.union(set_e)) # Output: {1, 2, 4, 34, 65, 7, 74, 45, 23, 'fag'}
print('Intersection:', set_d.intersection(set_e)) # Output: {65, 23}
print('Intersection:', set_d & set_e) # Output: {65, 23}
print('Difference:', set_d.difference(set_e)) # Output: {2, 4, 7, 45}
print('Difference:', set_d - set_e) # Output: {2, 4, 7, 45}
print('Symmetric Difference (XOR):', set_d.symmetric_difference(set_b)) # Output: {2, 65, 4, 'rifat', 7, 34, 74, 45, 23, 'fag'}
print('Symmetric Difference (XOR):', set_d ^ set_b) # Output: {2, 65, 4, 'rifat', 7, 34, 74, 45, 23, 'fag'}
Note: The order of elements in sets is not guaranteed. The output may vary from one execution to another. Sets automatically remove duplicate elements, and the elements are hashed internally, which may lead to different ordering.