Ordered, immutable sequences: fixed groups of values you can index and unpack.
# create a tuple
point = (3, 5)
rgb = (255, 128, 0)
single = (42,)
# ans: note the comma for a single element
empty = ()
# indexing tuples
point = (3, 5)
point[0]
# ans: 3
point[-1]
# ans: 5
# unpack values
x, y = (3, 5)
# ans: x=3, y=5
r, g, b = (255, 128, 0)
# ans: r=255, g=128, b=0
Each name on the left gets the value in the same position.
# cannot modify
point = (3, 5)
# ans: point[0] = 10 raises TypeError
# concatenation
tuple1 = (1, 2)
tuple2 = (3, 4)
tuple1 + tuple2
# ans: (1, 2, 3, 4)
# repetition
(1, 2) * 3
# ans: (1, 2, 1, 2, 1, 2)
Both build a new tuple; the originals are untouched.
# count
numbers = (1, 2, 3, 2, 4)
numbers.count(2)
# ans: 2
# index
numbers.index(3)
# ans: 2
Predict each result, then press → to check.
# single-element tuple?
x = (5)
type(x)
# ans: <class 'int'>
y = (5,)
type(y)
# ans: <class 'tuple'>
Parentheses alone just group; it's the comma that makes a tuple.
# tuple unpacking?
a, b = (10, 20)
# ans: a=10, b=20
# can you modify it?
t = (1, 2, 3)
t[0] = 10
# ans: TypeError (tuples are immutable)
# tuple slicing?
t = (1, 2, 3, 4, 5)
t[1:4]
# ans: (2, 3, 4)
# nested tuple?
t = ((1, 2), (3, 4))
t[0][1]
# ans: 2
t[0] is (1, 2); then [1] picks its second item.
# tuple containing a list?
t = (1, [2, 3], 4)
t[1].append(5)
# ans: t is (1, [2, 3, 5], 4)
The tuple still holds the same three objects; the list inside it is mutable and can change.
# length of an empty tuple?
t = ()
len(t)
# ans: 0
# tuple from a string?
t = tuple("abc")
# ans: ('a', 'b', 'c')
# comparing tuples?
(1, 2) == (1, 2)
# ans: True
(1, 2) < (1, 3)
# ans: True
Tuples compare item by item: the first items tie, so 2 < 3 decides.
# tuple membership?
3 in (1, 2, 3)
# ans: True
(5,) is a tuple; (5) is just 5.
No item assignment, no append. Use a list if it must change.
x, y = point assigns by position; the counts must match.
Indexing, slicing, len, in, count, index all work.