Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟒 BeginnerπŸ”΅ Advanced
🎯 Why Data Structures MatterπŸ“‹ Lists: Ordered CollectionsπŸ”‘ Dictionaries: Key-Value PairsπŸŽͺ Sets: Unique Values & SpeedπŸ“¦ Tuples: Immutable Sequencesβš–οΈ Comparing All Data StructuresπŸ”§ Mastering List Methods⚑ Advanced Dictionary PatternsπŸ”„ Power of Set OperationsπŸ—οΈ Building Nested Structuresβš™οΈ Performance Tuning & Optimization
Python/Data Structures/Tuples Immutability

πŸ“¦ Tuples and Immutability β€” Fixed Collections

Tuples are like lists but immutableβ€”once created, you cannot change them. This makes them perfect for protecting data.


🎯 Creating Tuples

Tuples use parentheses `()` instead of square brackets.

# Create tuples
colors = ("red", "green", "blue")
single_item = ("apple",)  # Note the comma!
coordinates = (10, 20, 30)

# Tuples are immutable
coordinates[0] = 15  # ❌ TypeError: 'tuple' object does not support item assignment

πŸ’‘ Why Immutability Matters

Immutable means you can't change it after creation. This is useful for:

  • **Data protection** β€” Prevents accidental modifications
  • **Dictionary keys** β€” Lists can't be keys, tuples can
  • **Function returns** β€” Multiple values safely
# A tuple makes a safe "fixed" coordinate
position = (10, 20)

# This works - create a new tuple
position = (15, 25)

# This fails - can't modify
position[0] = 15  # ❌ Error

🎨 Real-World Example: GPS Coordinates

# Store city coordinates (latitude, longitude)
cities = {
    "New York": (40.7128, -74.0060),
    "London": (51.5074, -0.1278),
    "Tokyo": (35.6762, 139.6503)
}

# Access coordinates safely
ny_coords = cities["New York"]
print(f"New York: {ny_coords}")  # (40.7128, -74.0060)

# Tuple unpacking
latitude, longitude = cities["London"]
print(f"Latitude: {latitude}, Longitude: {longitude}")

πŸ“Š Tuple vs List

FeatureTupleList
Brackets`()``[]`
Mutable❌ Noβœ… Yes
Fastβœ… FasterSlower
Dict Keyβœ… Can use❌ Cannot
MemoryLessMore

πŸ”‘ Key Takeaways

  • βœ… Tuples are immutableβ€”cannot change after creation
  • βœ… Use parentheses `()` to create tuples
  • βœ… Tuples can be dictionary keys
  • βœ… Faster and use less memory than lists
  • βœ… Perfect for protecting fixed data

Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep β€’ Build Real β€’ Verify Skills β€’ Launch Forward

Courses

PythonFastapiReactJSCloud

Β© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn