Python: Tuple

By Xah Lee. Date: . Last updated: .

What is Tuple

Tuple is like a List , except that it cannot be changed. Items cannot change, length cannot change.

Create Tuple by Literal Expression

()
Empty tuple.
(a,)
Tuple with 1 item a.
(a, b, c)
Tuple with item a, b, c.
a,
Tuple with 1 item a.
a, b, c
Tuple with item a, b, c.

Convert Iterable to Tuple

tuple(iterable)
Return a new tuple with items of iterable.
x = tuple([3, 4, 5])
y = 3, 4, 5

print(x)
# (3, 4, 5)

print(y)
# (3, 4, 5)

print(x == y)
# True

Tuple Cannot Change

Tuple cannot be changed, not item, and not length.

# tuple cannot be changed
xx = (3, 4, 5)
xx[0] = 9  # TypeError: 'tuple' object does not support item assignment

Nested Tuple and List

List and tuple can contain mixed datatypes, and nested in anyway.

# list and tuple can contain mixed datatypes, and nested in anyway

xx = [3, "4", [11, "12"], ("a", 2), 5]
yy = (3, "4", [11, "12"], ("a", 2), 5)

Python, Data Structure