While Lists are the "go-to" for collections, Python offers two other specialized structures: Tuples for data that shouldn't change, and Sets for unique, unordered items.
1. Tuples (The "Read-Only" List)
A Tuple is a collection which is ordered but immutable (unchangeable). You define them using parentheses () instead of square brackets.
When to use: Use tuples for data that should stay constant throughout the program, like coordinates
(x, y)or RGB color values.Safety: Because they are immutable, they are slightly faster than lists and protect your data from accidental changes.
2. Sets (The "Unique" Collection)
A Set is a collection which is unordered, unindexed, and contains no duplicate elements. You define them using curly braces {}.
When to use: Use sets when you want to ensure there are no duplicates in your data (like a list of unique visitor IDs) or when you need to perform mathematical operations like Unions or Intersections.
# --- TUPLES ---
coordinates = (10, 20)
print(f"X: {coordinates[0]}")
# coordinates[0] = 15 # This would cause a TypeError!
# --- SETS ---
# Notice the duplicate 'apple'
fruits_set = {"apple", "banana", "cherry", "apple"}
print(fruits_set) # Output: {'banana', 'apple', 'cherry'} (Order may vary)
# Adding to a set
fruits_set.add("orange")
# Membership testing (very fast in sets)
if "banana" in fruits_set:
print("Banana is in the set!")