Set Equality - Order Doesn't Matter¶
CS 5001/5002 - Strings, Sequences & Sets
Code¶
#!/usr/bin/env python3
"""
Filename: set_equality_order.py
Description: Set Equality - Order Doesn't Matter
CS 5001/5002 - Strings, Sequences & Sets
This script demonstrates that sets are equal if they contain the same elements,
regardless of order, and compares this behavior with lists.
"""
def main():
# Order independence in sets
S2 = {1, 2}
S3 = {2, 1}
print(f"S2 = {S2}")
print(f"S3 = {S3}")
print(f"S2 == S3: {S2 == S3}") # True - same elements
# Compare with lists (sequences) where order matters
list1 = [1, 2]
list2 = [2, 1]
print(f"List [1, 2] == [2, 1]: {list1 == list2}") # False - different order
# Converting between sets and lists
my_set = {3, 1, 4, 1, 5}
my_list = list(my_set)
print(f"Set {my_set} as list: {my_list}") # Order may vary
print(f"Sorted list: {sorted(my_set)}") # Consistent ordering
if __name__ == "__main__":
main()
How to Use¶
- Copy the code above
- Save it as a
.pyfile (e.g.,set_equality_order.py) - Run it with:
python set_equality_order.py
Part of CS 5001/5002 - Strings, Sequences & Sets materials