List Mutability and Comparison with Sets¶
CS 5001/5002 - Strings, Sequences & Sets
Code¶
#!/usr/bin/env python3
"""
Filename: list_mutability_sets.py
Description: List Mutability and Comparison with Sets
CS 5001/5002 - Strings, Sequences & Sets
This script demonstrates the mutable nature of lists and compares their
behavior with sets, particularly regarding duplicates and ordering.
"""
def main():
# Lists are mutable sequences
data = [13, 15, -4, 31, 5, 6, 19]
print(f"Original list: {data}")
# We can modify individual elements
data[0] = 42
print(f"After modifying index 0: {data}")
# Lists preserve order and allow duplicates
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
print(f"List with duplicates: {numbers}")
print(f"Length: {len(numbers)}")
# Convert to set to remove duplicates
unique_numbers = set(numbers)
print(f"As set (unique): {unique_numbers}")
print(f"Unique count: {len(unique_numbers)}")
# Convert back to list (order may change)
back_to_list = list(unique_numbers)
print(f"Back to list: {back_to_list}")
# Sorted version for consistent ordering
sorted_unique = sorted(unique_numbers)
print(f"Sorted unique: {sorted_unique}")
if __name__ == "__main__":
main()
How to Use¶
- Copy the code above
- Save it as a
.pyfile (e.g.,list_mutability_sets.py) - Run it with:
python list_mutability_sets.py
Part of CS 5001/5002 - Strings, Sequences & Sets materials