Tuples

Like a list, but locked — once built, a tuple's contents can't be changed.

Introduction

A tuple is an ordered collection written with round brackets. It behaves like a list in almost every way, except it's immutable — once created, its contents can't change.

t = (1, "two", 3.0)
print(t)
(1, 'two', 3.0)

A single-element tuple needs a trailing comma, or Python just treats the parentheses as grouping, not a tuple:

not_a_tuple = (5)
is_a_tuple = (5,)
print(type(not_a_tuple))
print(type(is_a_tuple))
<class 'int'> <class 'tuple'>

You can also build one from another sequence with tuple():

print(tuple("abc"))
print(tuple([1, 2, 3]))
('a', 'b', 'c') (1, 2, 3)

Indexing & Slicing

Indexing and slicing work exactly like lists and strings — but since tuples are immutable, you can read from an index, not assign to it.

t = ('b', 'y', 't', 'e')
print(t[0])
print(t[-1])
print(t[1:3])
b e ('y', 't')
t[0] = 'B'
TypeError: 'tuple' object does not support item assignment

Operators

+ joins two tuples, and * repeats one. To add a single value, remember it needs the trailing comma to count as a tuple.

t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2)
print(t1 * 2)
print(t1 + (5,))
(1, 2, 3, 4) (1, 2, 1, 2) (1, 2, 5)

in / not in and comparisons work the same way they do for lists — comparing element by element until one pair differs.

print(3 in (1, 2, 3))
print((1, 2, 9) > (1, 2, 5))
True True

Methods

Because tuples can't be modified, there are only two methods — everything else that "changes" a tuple has to build a new one instead.

count() returns how many times a value appears, and index() returns the position of its first occurrence.

t = (2, 4, 2, 6, 2, 8)
print(t.count(2))
print(t.index(6))
3 3

One handy related trick is unpacking — assigning a tuple's values straight into separate variables in one line.

point = (3, 7)
x, y = point
print(x, y)
3 7