PYTHON

Using Tuples as Immutable Keys and Multi-Value Returns

Explore the versatility of Python tuples as immutable data structures, demonstrating their use as unique, hashable dictionary keys and for returning multiple values from functions.

# --- Part 1: Tuples as Immutable Dictionary Keys ---
# Tuples are hashable, making them suitable as dictionary keys.
# Lists are mutable and thus not hashable, cannot be dict keys.

coordinates = {}
coordinates[(0, 0)] = 'Origin'
coordinates[(10, 20)] = 'Point A'
coordinates[(5, -3)] = 'Point B'

print(f"Coordinates dictionary: {coordinates}")
print(f"Value at (10, 20): {coordinates[(10, 20)]}")

# Trying to use a list as a key will raise a TypeError
# try:
#     my_dict = {['a', 'b']: 1}
# except TypeError as e:
#     print(f"Error using list as key: {e}") # unhashable type: 'list'


# --- Part 2: Functions Returning Multiple Values as a Tuple ---
def get_user_info(user_id):
    """Simulates fetching user details and returns them as a tuple."""
    if user_id == 1:
        return "Alice", 30, "Software Engineer"
    elif user_id == 2:
        return "Bob", 25, "Data Scientist"
    return None, None, None

# Unpacking the tuple directly
name, age, occupation = get_user_info(1)
print(f"
User 1: Name={name}, Age={age}, Occupation={occupation}")

# Accessing as a tuple
user2_data = get_user_info(2)
print(f"User 2 as tuple: {user2_data}")
print(f"User 2 Name: {user2_data[0]}")

# Handling a non-existent user
unknown_user_data = get_user_info(99)
print(f"Unknown user data: {unknown_user_data}")
How it works: This snippet highlights two crucial applications of Python tuples. First, because tuples are immutable and hashable, they can serve as dictionary keys, enabling complex composite keys like geographical coordinates. Second, functions in Python naturally return multiple values as a tuple, which can then be conveniently unpacked into individual variables. This provides a clean and concise way to return structured data from a function without needing to create a custom class or dictionary.

Need help integrating this into your project?

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

Hire DigitalCodeLabs