Python tuples are an “immutable” data type, meaning you cannot change their contents once created. However, just because you cannot “change” them doesn’t mean you can’t use them. Just like lists, you can freely “access” elements, “slice” them, and check the “number of elements”.
This article explains the basic methods for accessing and manipulating tuples.
1. Getting the Number of Elements (len())
To check how many elements are stored in a tuple (its length), use the built-in function len(), just like with lists or strings.
Syntax:
len(tuple_variable)
Example:
# List of running services
active_services = ("httpd", "mysql", "sshd", "redis")
# Get count with len()
service_count = len(active_services)
print(f"Tuple Content: {active_services}")
print(f"Running Services Count: {service_count}")
Output:
Tuple Content: ('httpd', 'mysql', 'sshd', 'redis')
Running Services Count: 4
2. Accessing Elements (Indexing)
To access a specific element in a tuple, use the index (position number) exactly like you do with a list.
Positive Index (Starts from 0)
[0] refers to the first element, and [1] refers to the second.
# 0th (First) element
first_service = active_services[0]
print(f"Index 0: {first_service}")
Output:
Index 0: httpd
Negative Index (Starts from -1)
[-1] refers to the last element, and [-2] refers to the second to last.
# -1st (Last) element
last_service = active_services[-1]
print(f"Index -1: {last_service}")
Output:
Index -1: redis
3. Slicing Elements
You can use the “slicing” syntax to extract a part of a tuple as a new tuple, just like with lists.
Syntax: tuple_variable[start:stop:step]
start is included, but stop is excluded (it goes up to that point).
active_services = ("httpd", "mysql", "sshd", "redis", "nginx")
# Index: 0 1 2 3 4
# From index 1 ("mysql") up to index 3 ("redis")
# Extracts [1] and [2]
core_services = active_services[1:3]
print(f"Original Tuple: {active_services}")
print(f"Slice Result: {core_services}")
print(f"Result Type: {type(core_services)}")
Output:
Original Tuple: ('httpd', 'mysql', 'sshd', 'redis', 'nginx')
Slice Result: ('mysql', 'sshd')
Result Type: <class 'tuple'>
It is important to note that the result of slicing is also a tuple, not a list.
Summary: Tuples are “Read-Only”
Let’s summarize the operational differences between tuples and lists.
Allowed Operations (Same as List):
len(t)(Get length)t[0](Index access)t[-1](Negative index access)t[1:3](Slicing)for item in t:(Looping)if "value" in t:(Searching within)
Not Allowed Operations (Tuple-specific errors):
t[0] = "new"(TypeError): Changing elementst.append("new")(AttributeError): Adding elementsdel t[0](TypeError): Deleting elements
While you cannot “change” the contents of a tuple, you can “read” them in exactly the same way as a list.
