DEV Community

Cover image for 🐍 Tuples & Named Tuples in Python: The Clever Way to Structure Data
Anik Sikder
Anik Sikder

Posted on

🐍 Tuples & Named Tuples in Python: The Clever Way to Structure Data

When you start coding in Python, you quickly learn about lists and tuples.
Most tutorials say: "Tuples are just like lists, but you can’t change them."

That’s true but it’s also an oversimplification.
Tuples are more efficient, more predictable, and ideal for organizing fixed data.

And when you bring named tuples into the picture, you get readable, self-documenting code without writing a class.

In this article, we’ll explore:

  • 🎯 Why tuples exist (and why they’re not just frozen lists)
  • 🥊 Tuples vs lists: practical use cases
  • 🧠 Memory usage and performance insights
  • 🏷 Named tuples and why they’re amazing
  • 💡 Real-world examples and professional tips

Let’s dig in and make tuples fun.


🎬 1. Tuples: The Lightweight Data Container

A tuple is an ordered, immutable collection of items.

book = ("Clean Code", "Robert C. Martin", 2008)
Enter fullscreen mode Exit fullscreen mode

Tuples don’t allow item reassignment and that’s a good thing.
Because of that immutability, Python can store them in a tighter, more efficient way compared to lists.


✅ Advantages of Tuples

  • Immutable & Reliable Your data can’t be accidentally changed
  • Compact Python doesn’t reserve extra memory for future growth
  • Fast Slightly quicker than lists for lookup and iteration
  • Hashable Great for dictionary keys or elements of a set

🥊 Tuples vs Lists, Choosing the Right Tool

Tuples and lists often feel interchangeable, but they serve different purposes.

Feature Tuple 🎁 List 📋
Mutability ❌ Cannot change after creation ✅ Fully mutable
Memory Footprint Fixed, minimal Pre-allocated with extra capacity
Performance Slightly faster Slightly slower
Hashable Yes (if contents are hashable) No
Best Use Fixed-size, read-only data Dynamic, changing data

🔍 Memory Insights

Let’s check actual memory usage with sys.getsizeof:

import sys

lst = [1, 2, 3]
tpl = (1, 2, 3)

print(sys.getsizeof(lst))  # ~88-96 bytes (extra room included)
print(sys.getsizeof(tpl))  # ~72-80 bytes (no extra space)
Enter fullscreen mode Exit fullscreen mode

Lists allocate extra capacity so you can .append() quickly without resizing every time.
Tuples skip that overhead, storing exactly the space they need.


📌 When to Choose What

  • Use list if you need to grow, shrink, or reorder data.
  • Use tuple if you want data to stay fixed and safe.

💡 Quick analogy:

  • List = Backpack 🎒 you can keep adding/removing stuff.
  • Tuple = Sealed box 📦 once packed, it stays the same.

🛠 2. Real-World Tuple Examples

Example 1: Returning Multiple Results

def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers)/len(numbers)

low, high, avg = get_stats([2, 4, 8, 10])
print(f"Low={low}, High={high}, Avg={avg}")
Enter fullscreen mode Exit fullscreen mode

Instead of building a class or returning a list, a tuple keeps it simple.


Example 2: Representing a Data Point

location = (23.8103, 90.4125)  # Latitude, Longitude
lat, lon = location
print(f"Coordinates: {lat}, {lon}")
Enter fullscreen mode Exit fullscreen mode

Perfect for coordinates, colors (r,g,b), or any grouped values that belong together.


Example 3: Working With Database Rows

rows = [
    ("Anik", 27, "Developer"),
    ("Sara", 31, "Designer")
]

for name, age, role in rows:
    print(f"{name} ({age}) works as a {role}")
Enter fullscreen mode Exit fullscreen mode

Database libraries often use tuples for results since they are fixed and predictable.


🏷 3. Named Tuples: Tuples with Labels

Accessing row[0] and row[1] works but it’s not very descriptive.
Enter namedtuple from collections.

from collections import namedtuple

Employee = namedtuple("Employee", ["name", "age", "role"])
emp = Employee("Anik", 27, "Developer")

print(emp.name)  # Anik
print(emp.role)  # Developer
Enter fullscreen mode Exit fullscreen mode

Now you get attribute-style access without writing a full class.


🌟 Why Named Tuples Rock

  • Readable emp.name is easier than emp[0]
  • Immutable still as safe as a regular tuple
  • Lightweight faster and smaller than custom classes
  • Unpackable behaves like a normal tuple if needed

Updating Named Tuples

Since they’re immutable, you create a modified copy with _replace:

emp_older = emp._replace(age=28)
print(emp_older)
Enter fullscreen mode Exit fullscreen mode

Named Tuples vs Dictionaries

Named Tuple Dictionary
Lightweight & immutable Flexible & mutable
Access by attribute Access by key
Can be dict key Cannot be dict key
Fixed fields Dynamic fields

Named tuples shine when your fields are known and won’t change at runtime.
Dictionaries are better for dynamic structures or user-generated data.


🎯 4. Pro Tips

  • Tuples are great for function returns, constants, and coordinates.
  • Named tuples are excellent for structured records with descriptive names.
  • Lists remain the best choice when your data is expected to grow or shrink.
  • Use sys.getsizeof if you’re curious about memory impact in performance-critical code.

🎉 Final Thoughts

Tuples are Python’s way of saying:

“Here’s a small, efficient box to keep your data safe.”

Named tuples take it further, letting you label that box so you always know what’s inside.

Next time you write data[0], ask yourself:
“Would a named tuple make this more readable?”
In many cases, it will and your future self (or teammate) will thank you.

Top comments (0)