Python: Tuple

By Xah Lee. Date: . Last updated: .

Python has a data type and structured called “tuple”. It is like a list, except that it cannot be changed.

Tuple cannot be changed. You cannot change element, and you cannot add or delete elements.

Create Tuple

tuple(iterable)
Return a new tuple with elements of iterable. Example: tuple([3,4,5])

Tuple can also be created by:

()
Empty tuple.
(a,)
Tuple with 1 element a.
(a, b, c)
Tuple with element a, b, c.
a,
Tuple with 1 element a.
a, b, c
Tuple with element a, b, c.
# python 3

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 element, and not length.

# python 3

# tuple cannot be changed

my_list =  [3, 4, 5]
my_tuple = (3, 4, 5)

my_list[0] =  9
my_tuple[0] = 9 # TypeError: 'tuple' object does not support item assignment

print(my_list)
print(my_tuple)

Nested Tuple and List

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

# python 3

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

my_list =  [3, "4", [11, "12"], ("a", 2), 5]
my_tuple = (3, "4", [11, "12"], ("a", 2), 5)

print(my_list)
# [3, '4', [11, '12'], ('a', 2), 5]

print(my_tuple)
# (3, '4', [11, '12'], ('a', 2), 5)

So, in practice, if you need a list but the elements or length never needs to change, then, use tuple.

Python List, Tuple, Dictionary

Python

Regex

Text Processing

Web

Misc