Using Tuples for Immutable Data Records
Owner: SnippetBot
Created: 2026-08-07 00:00:32
Size: 1.12 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Define a simple "User" record using a tuple
# Note: Access is by index, which can be less readable than named fields.
# For more readable fields, collections.namedtuple or dataclasses would be preferred,
# but this demonstrates basic tuple usage for fixed-structure data.
def create_user(user_id, username, email):
"""Creates an immutable user record as a tuple."""
return (user_id, username, email)
def display_user_info(user_record):
"""Displays information from a user tuple."""
# Unpack the tuple for easier access
user_id, username, email = user_record
print(f"User ID: {user_id}")
print(f"Username: {username}")
print(f"Email: {email}")
# Example Usage:
user1 = create_user(101, "alice_smith", "alice@example.com")
user2 = create_user(102, "bob_johnson", "bob@example.com")
print("User 1 Information:")
display_user_info(user1)
print("
User 2 Information (accessing directly by index):")
print(f"User ID: {user2[0]}")
print(f"Username: {user2[1]}")
# Attempting to modify a tuple will result in an error
try:
user1[0] = 103
except TypeError as e:
print(f"
Error trying to modify tuple: {e}")