From Lists to Sets - Understanding the Differences¶
CS 5001/5002 - Strings, Sequences & Sets
Code¶
#!/usr/bin/env python3
"""
From Lists to Sets - Understanding the Differences
CS 5001/5002 - Strings, Sequences & Sets
This file demonstrates the key differences between lists and sets:
- Lists: ordered, allow duplicates, indexable
- Sets: unordered, unique elements only, no indexing
- When to use each data structure
"""
# You're familiar with lists - they keep order and allow duplicates
my_list = [1, 2, 2, 3, 1, 4]
print(f"List: {my_list}")
print(f"Length: {len(my_list)}") # 6 elements
print(f"First element: {my_list[0]}") # Can access by index
# Sets are different - no duplicates, no order
my_set = {1, 2, 2, 3, 1, 4} # Same elements as list
print(f"Set: {my_set}") # Duplicates automatically removed
print(f"Length: {len(my_set)}") # Only 4 unique elements
# Can't access set elements by index - this would cause an error:
# print(my_set[0]) # TypeError: 'set' object is not subscriptable
# But you can check if something is in the set (very fast!)
print(f"Is 2 in the set? {2 in my_set}") # True
print(f"Is 5 in the set? {5 in my_set}") # False
# Converting between lists and sets
list_with_duplicates = [1, 1, 2, 2, 3, 3, 4, 4]
unique_set = set(list_with_duplicates) # Remove duplicates
back_to_list = list(unique_set) # Convert back (order may change)
print(f"Original list: {list_with_duplicates}")
print(f"As set (unique): {unique_set}")
print(f"Back to list: {back_to_list}")
How to Use¶
- Copy the code above
- Save it as a
.pyfile (e.g.,lists_vs_sets.py) - Run it with:
python lists_vs_sets.py
Part of CS 5001/5002 - Strings, Sequences & Sets materials