Python Tutorial
Python Access Tuples
Tuple items are indexed like lists. You can also slice and test membership.
Access and Slice
First item is index 0. Negative indexes count from the end.
thistuple = ("apple", "banana", "cherry", "orange")
print(thistuple[1])
print(thistuple[-1])
print(thistuple[1:3])Check if Item Exists
Use in.
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes")📘 Real-World Deep Dive
Tuples are immutable indexed sequences — <code>t[i]</code>, <code>t[i:j]</code>, <code>t.count/index</code>, and the minor <code>namedtuple</code>. Picking <code>tuple</code> over <code>list</code> is a small type-driven signal of intent.
Real-Life Scenario
A small lat/lon pair — always two floats, never changing. The right type is tuple (or NamedTuple), never list.
Real-Life Example
from typing import NamedTuple
class Geo(NamedTuple):
lat: float
lon: float
P = Geo(40.7128, -74.0060)
# Access by index
print("lat:", P[0], "lon:", P[1])
# Access by name (NamedTuple gives both)
print("dict view :", P._asdict())
print("city :", P.lat, P.lon)
# Slicing produces a tuple
half = P[0:1] # (lat,)
print("half :", half, type(half).__name__)
# tuple.count / tuple.index
xs = (1, 2, 3, 5, 8, 13, 21, 34)
print("count of 2 :", xs.count(2))
print("index of 21 :", xs.index(21))Expected Output
lat: 40.71 lon: -74.0
dict view : {'lat': 40.7128, 'lon': -74.0}
city : 40.7128 -74.0
half : (40.7128,) tuple
count of 2 : 1
index of 21 : 6Common mistakes
- Slicing a tuple returns a tuple;
t[1:1]is an empty tuple, not aNone. tuple.indexraisesValueErrorif absent;incheck first if uncertain.- Tuple of one element must include the trailing comma:
x = (1,).
🚀 Performance & Best Practices
- Tuple indexing is O(1);
len(t)is cached as an attribute. - Tuple-unpacking is faster than per-index access for fixed-size records.
- Tuples of identical type can be
intern-ed by the interpreter; use tuples for short-lived records.
🧪 Try It Yourself
- Refactor the example to compute the great-circle distance between
Pand anotherGeo. - Implement
t.addsemantics by using aNamedTuplesubclass with_replace. - Profile
t[:]vs.tuple(t)for a 100 k-element tuple.