TutorialsPythonTuples and Sets

Tuples and Sets

Use tuples for fixed data and sets for unique value operations

Tuples and sets are less used than lists, but they solve specific problems elegantly. Tuples are immutable lists — perfect for fixed data like column name mappings, coordinates, or database field definitions that should never change. Sets store only unique values — perfect for finding duplicates, unique categories, and set operations like intersection and difference.

Examples

Tuples — immutable ordered collections
# Create tuple (parentheses or just commas)
dimensions = (1920, 1080)
date_parts = (2026, 8, 15)
single = (42,)   # single-item tuple needs trailing comma

# Access (same as list)
dimensions[0]    # 1920
dimensions[-1]   # 1080

# Tuple unpacking — very Pythonic
year, month, day = date_parts
print(year)   # 2026
print(month)  # 8

# Functions returning multiple values use tuples
def min_max(lst):
    return min(lst), max(lst)   # returns a tuple

low, high = min_max([45, 18, 62, 9])
print(low, high)   # 9 62

# Tuples as dict keys (lists cannot be dict keys)
location_sales = {("Delhi", "Q1"): 450000, ("Noida", "Q1"): 320000}
💡 Tuples are faster than lists and signal "this data should not change." Use them for fixed configs and function return values.
Sets — unique values and set operations
cities_2025 = {"Delhi", "Noida", "Gurgaon", "Faridabad"}
cities_2026 = {"Delhi", "Noida", "Ghaziabad", "Greater Noida"}

# Set from list — removes duplicates instantly
raw = ["Delhi", "Noida", "Delhi", "Delhi", "Gurgaon"]
unique = set(raw)   # {"Delhi", "Noida", "Gurgaon"}
print(len(raw), len(unique))   # 5  3

# Set operations
cities_2025 & cities_2026   # Intersection (in both): {"Delhi", "Noida"}
cities_2025 | cities_2026   # Union (in either): all 6 cities
cities_2025 - cities_2026   # Difference (in 2025 not 2026): {"Gurgaon", "Faridabad"}
cities_2026 - cities_2025   # New in 2026: {"Ghaziabad", "Greater Noida"}

# Membership check (faster than list for large data)
"Delhi" in cities_2025   # True
"Pune"  in cities_2025   # False
💡 Sets are unordered — you cannot access items by index. But membership checks (in) are O(1) — much faster than lists for large collections.

Key Points

  • Tuple = immutable list (parentheses). Set = unique values (curly braces)
  • Tuple unpacking: a, b, c = (1, 2, 3) assigns all at once
  • set() on a list removes all duplicates in one step
  • Set intersection (&), union (|), difference (-) are powerful for data comparison
  • In Pandas: df["City"].unique() returns array of unique values like a set

Practice Question

You have a list with 1000 city names, many repeated. What is the fastest way to get only unique city names?

Related Topics

Python ListsStore, access and manipulate collections of data with Python listsDictionaries in PythonKey-value pairs for fast lookups, mappings and structured dataNumPy ArraysFast numerical computation with NumPy arrays — the engine behind Pandas