Tuples and Sets are powerful data structures that complement lists and dictionaries. While tuples are immutable sequences perfect for fixed data, sets are unordered collections ideal for mathematical operations and duplicate removal. In this complete guide, you will master both structures.

🔒 Tuples: Immutable Lists

Tuples are like sealed data capsules in the Python Universe—once created, they cannot be modified. Use tuples when data should remain constant.

# Creating tuples
coordinates = (10, 20)
planet = ("Earth", 12742, 5.97e24)
single_element = (42,)  # Mandatory comma!

# Unpacking values
x, y = coordinates
print(f"X: {x}, Y: {y}")

When to Use Tuples

  • ✅ Data that should not change (coordinates, settings).
  • ✅ Returning multiple values from functions.
  • ✅ Performance (slightly faster than lists).

🎯 Sets: Mathematical Collections

Sets are unordered collections of unique elements. They are perfect for eliminating duplicates and performing set operations like union and intersection.

# Creating sets
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "orange"}

# Duplicates are automatically removed
with_duplicates = {1, 2, 2, 3, 3}
print(with_duplicates)  # {1, 2, 3}

Set Operations

  • Union (|): Elements in A or B.
  • Intersection (&): Elements in both A and B.
  • Difference (-): Elements in A but not in B.

🚀 Conclusion

Tuples and sets complete your arsenal of data structures in Python. Each has its specific purpose—choose the right tool for the right problem! For more on related structures, check our guides on Lists and Dictionaries. Also, refer to the official Python documentation.