← Back to all snippets
PYTHON

Using Tuples for Immutable Data and Multiple Returns in Python

Discover how Python tuples provide immutable data structures for safe storage and efficient multi-value returns, improving function clarity and data integrity in your web projects.

# Basic tuple creation and immutability
coordinates = (10.0, 20.5)
user_status = ('active', 101, True)
print(f"Coordinates: {coordinates}, Type: {type(coordinates)}")
print(f"User Status: {user_status}")

# Attempting to modify a tuple will raise an error
try:
    coordinates[0] = 11.0
except TypeError as e:
    print(f"Error trying to modify tuple: {e}")

# Tuples for multiple return values from a function
def get_user_info(user_id):
    # In a real app, this would fetch from a database
    if user_id == 1:
        return "Alice", "[email protected]", 30
    return None, None, None

name, email, age = get_user_info(1)
print(f"User Info: Name={name}, Email={email}, Age={age}")

# Using namedtuples for improved readability
from collections import namedtuple

# Define a namedtuple for a point
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(10, 20)
print(f"NamedTuple Point: x={p1.x}, y={p1.y}")

# Define a namedtuple for a database record
Product = namedtuple('Product', 'id name price stock')
product1 = Product(id=101, name='Laptop', price=1200.00, stock=50)
print(f"Product Info: ID={product1.id}, Name={product1.name}, Price={product1.price}, Stock={product1.stock}")

# Namedtuples are immutable, just like regular tuples
try:
    product1.price = 1150.00
except AttributeError as e:
    print(f"Error trying to modify namedtuple field: {e}")
How it works: This snippet illustrates the utility of Python tuples, highlighting their key characteristic: immutability. Tuples are excellent for fixed collections of items that should not change, such as coordinates or database record structures. It demonstrates how functions can return multiple values naturally as a tuple, which can then be easily unpacked. Furthermore, it introduces `collections.namedtuple`, a powerful extension that provides readable, self-documenting tuple subclasses by allowing access to elements by name instead of just index, enhancing code clarity without losing tuple's immutable benefits.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs