A Python tuple is an ordered, immutable sequence. Tuples support indexing, slicing, iteration and unpacking, but their items cannot be replaced, appended or removed in place.
Create a tuple by separating values with commas. Parentheses are commonly used for clarity:
my_tuple = ('Alex', 'Ronald', 'John')
print(my_tuple)('Alex', 'Ronald', 'John')Tuples are useful for fixed records, returning multiple values from functions, sequence unpacking, and values that should not be changed accidentally.
Show Table of ContentsAn empty tuple can be written as () or created with the tuple() constructor. Use type() to inspect the result.
my_tuple = tuple()
print(type(my_tuple))<class 'tuple'>my_tuple = ()
print(my_tuple)()A tuple can hold values of different types:
record = ('Alex', 32, True)
print(record)('Alex', 32, True)The constructor accepts an iterable such as range():
x = range(5, 50, 10)
my_tuple = tuple(x)
print(my_tuple)(5, 15, 25, 35, 45)The comma creates a tuple, not the parentheses. A one-item tuple therefore needs a trailing comma.
not_a_tuple = ('abc')
single_item = ('abc',)
print(type(not_a_tuple))
print(type(single_item))<class 'str'>
<class 'tuple'>Unlike a set, a tuple records positions. Index 0 is the first element and -1 is the last.
my_tuple = ('Alex', 'Ronald', 'John')
print(my_tuple[1])
print(my_tuple[-1])Ronald
Johnmy_tuple = ('a', 'c', 'd', 'c', 'x', 'k', 'd', 'c')
print(my_tuple[0])
print(my_tuple[-1])
print(my_tuple[2])
print(my_tuple[1:])
print(my_tuple[3:6])a
c
d
('c', 'd', 'c', 'x', 'k', 'd', 'c')
('c', 'x', 'k')Values can be packed into a tuple and unpacked into separate variables.
person = ('Alex', 32, 'London')
name, age, city = person
print(name)
print(age)
print(city)Alex
32
LondonThe unpacking operator * can also pass all tuple elements to print():
my_tuple = (4, 2, 5, 1, 3)
print(*my_tuple)4 2 5 1 3Convert to a list when you need in-place changes, then convert back if a tuple is required.
my_tuple = ('a', 'b', 'c')
my_list = list(my_tuple)
print(type(my_list))
print(my_list)<class 'list'>
['a', 'b', 'c']my_list = ['a', 'b', 'c']
my_tuple = tuple(my_list)
print(type(my_tuple))
print(my_tuple)<class 'tuple'>
('a', 'b', 'c')Use a for loop to process each item in order.
my_tuple = ('Alex', 'Ronald', 'John')
for name in my_tuple:
print(name)Alex
Ronald
JohnAfter a tuple is created, individual positions cannot be assigned a new value.
my_tuple = ('Alex', 'Ronald', 'John')
my_tuple[1] = 'Ravi'This raises TypeError: 'tuple' object does not support item assignment.
Tuples also do not have list methods such as append() or insert().
my_tuple = (1, 2, 3)
my_tuple.append(4)This raises AttributeError. Concatenation creates a new tuple rather than changing the existing object. You can also inspect object identity with id():
my_tuple = (5, 7, 5, 4, 3, 5)
old_tuple = my_tuple
my_tuple += (9, 8)
print(old_tuple is my_tuple)
print(my_tuple)False
(5, 7, 5, 4, 3, 5, 9, 8)The tuple structure is immutable, but a mutable object stored inside it can still change.
data = ([1, 2], [3, 4])
data[0].append(5)
print(data)([1, 2, 5], [3, 4])This distinction is important when deciding whether a tuple is also hashable: a tuple can be hashed only when all of its elements are hashable.
my_tuple = ('Alex', 'Ronald', 'John')
if 'Ronald' in my_tuple:
print('Yes, present in tuple')
else:
print('Not present')Yes, present in tupleFor numeric tuples, len(), max(), min() and sum() can be used directly.
numbers = (8, 2, 4, 3, 7, 3)
print(max(numbers))
print(min(numbers))
print(sum(numbers))
print(len(numbers))8
2
27
6names = ('Alex', 'Ronald', 'John')
print(len(names))3count() and index() Top ↑Tuple provides two commonly used sequence-specific methods.
my_tuple = (5, 7, 5, 4, 3, 5)
print(my_tuple.count(5))3my_tuple = (5, 7, 5, 4, 3, 5)
print(my_tuple.index(3))4del can remove the variable binding. Accessing the variable afterward raises NameError.
my_tuple = ('Alex', 'Ronald', 'John')
del my_tuple
print(my_tuple)str.join() is the clearest approach when all elements are strings.
my_tuple = ('Welcome ', 'to ', 'plus2net')
my_str = ''.join(my_tuple)
print(my_str)Welcome to plus2netThe original alternatives are also valid. The first uses str.format():
my_str = '{}{}{}'.format(*my_tuple)
print(my_str)Welcome to plus2netmy_str = ''
for element in my_tuple:
my_str += element
print(my_str)Welcome to plus2netA list of tuples is useful for rows or fixed records.
from datetime import date, timedelta
rows = []
today = date.today()
for delta in range(-3, 3):
day = today + timedelta(days=delta)
rows.append((delta, day.isoformat(), day.strftime('%b-%Y')))
print(rows)The dates depend on the day the program runs. Each list element is a three-item tuple.
('Alex') is a string, not a tuple; use ('Alex',).append() on tuples.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.