Python Tutorial: Python Tuples
A tuple in Python is an ordered, immutable (unchangeable) collection of items written inside round brackets ((...)). Like lists, tuples allow duplicate values and can hold items of mixed data types, but once created, their elements cannot be added, removed, or modified directly.
1. Creating & Accessing Tuple Items
Tuple elements use zero-based indexing and negative indexing just like lists, and can also be sliced:
print(colors) # ('Red', 'Green', 'Blue', 'Yellow')
print(len(colors)) # 4
print(colors[0]) # Red
print(colors[-1]) # Yellow
print(colors[1:3]) # ('Green', 'Blue')
2. Single-Item Tuple Gotcha
To create a tuple with only one item, you must include a trailing comma , after the item — otherwise Python treats the parentheses as normal grouping brackets:
not_a_tuple = ("Python")
print(type(single_tuple)) # <class 'tuple'>
print(type(not_a_tuple)) # <class 'str'>
3. Tuple Unpacking & Asterisk (*)
Tuples are frequently used to unpack multiple values into variables in a single statement, including function return values:
x, y, z = point
print(x, y, z) # 10 20 30
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
4. Tuple Methods & Immutability Workaround
Tuples have only two built-in methods: count() and index(). If you need to edit a tuple, convert it to a list, modify it, and convert it back to a tuple:
print(grades.count("A")) # 3
print(grades.index("C")) # 3
temp_list = list(grades)
temp_list.append("B+")
updated_grades = tuple(temp_list)
print(updated_grades)