8.1 Introduction to Tuples
A tuple is a Python collection that stores several values in one variable. Tuples keep their items in order, allow duplicate values, and can contain different data types. The important difference is that a tuple cannot normally be changed after it is created. Tuples are useful for fixed information such as coordinates, dates, colors, and settings.
Example
colors = ("red", "green", "blue")
print(colors)
Output
('red', 'green', 'blue')
Output explanation: Python displays the three tuple items inside parentheses. The items remain in their original order.
8.2 Creating Tuples
You usually create a tuple by placing values inside parentheses and separating them with commas. A tuple may contain strings, numbers, Boolean values, or other objects. Parentheses improve readability, although commas are what truly create the tuple. After assigning it to a variable, you can access, loop through, compare, or unpack its values.
Example
student = ("Sara", 14, True)
print(student)
Output
('Sara', 14, True)
Output explanation: The tuple contains a string, an integer, and a Boolean value. Python allows different data types inside one tuple.
8.3 Single-Item Tuples
A single-item tuple needs a comma after its only value. Parentheses alone do not create a tuple because Python may treat them as normal grouping symbols. This small comma is essential. Single-item tuples are useful when a function or program expects a tuple even when only one value is available.
Example
item = ("apple",)
print(item)
print(type(item))
Output
('apple',)
<class 'tuple'>
Output explanation: The comma tells Python that the value is a tuple. The type output confirms that it is not a plain string.
8.4 Accessing Tuple Items
You access a tuple item by writing the tuple name followed by its index inside square brackets. Python starts counting at zero, so index zero selects the first item. Accessing a value does not change the tuple. You can print the value, store it in another variable, compare it, or use it in a calculation.
Example
cities = ("Toronto", "Ottawa", "Montreal")
print(cities[1])
Output
Ottawa
Output explanation: Index 1 selects the second item because Python begins counting positions at zero.
8.5 Negative Indexing
Negative indexing counts backward from the end of a tuple. Index minus one selects the last item, minus two selects the second-last item, and the pattern continues. Negative indexing is convenient when you need a value near the end but do not want to calculate the tuple’s exact length.
Example
numbers = (10, 20, 30, 40)
print(numbers[-1])
print(numbers[-2])
Output
40
30
Output explanation: Minus one selects 40, the final value. Minus two selects 30, the second-last value.
8.6 Tuple Slicing
Tuple slicing creates a new tuple containing part of an existing tuple. A slice commonly uses a start index and a stop index separated by a colon. The start position is included, but the stop position is excluded. Slicing is useful for selecting ranges of fixed data without changing the original tuple.
Example
letters = ("a", "b", "c", "d", "e")
print(letters[1:4])
Output
('b', 'c', 'd')
Output explanation: The slice begins at index 1 and stops before index 4, so it returns b, c, and d.
8.7 Tuple Immutability
Tuples are immutable, which means you cannot replace, add, or remove individual items after the tuple is created. This protects fixed data from accidental changes. You can still create a new tuple based on the old one. Immutability makes tuples useful when values should remain stable throughout a program.
Example
point = (4, 7)
new_point = (10, point[1])
print(point)
print(new_point)
Output
(4, 7)
(10, 7)
Output explanation: The original tuple remains unchanged. A new tuple is created with 10 as its first value.
8.8 Packing Tuples
Tuple packing means placing several values together into one tuple. Python can pack values even when parentheses are omitted, as long as commas separate the items. Packing is useful for grouping related information such as a person’s name, age, and city into one object that can be passed around together.
Example
person = "Ali", 25, "Toronto"
print(person)
Output
('Ali', 25, 'Toronto')
Output explanation: Python packs the three comma-separated values into one tuple and displays them inside parentheses.
8.9 Unpacking Tuples
Tuple unpacking assigns the items of a tuple to separate variables in one statement. The number of variables must normally match the number of tuple items. Unpacking makes code easier to read because each value receives a meaningful name. It is often used with coordinates, function results, database rows, and grouped settings.
Example
person = ("Mina", 18, "Ottawa")
name, age, city = person
print(name)
print(age)
print(city)
Output
Mina
18
Ottawa
Output explanation: The first item goes to name, the second to age, and the third to city.
8.10 Extended Unpacking
Extended unpacking uses an asterisk before one variable so that it can collect several remaining items. This is helpful when you want the first and last values separately while grouping the middle values together. The starred variable receives a list, even when the original collection is a tuple.
Example
numbers = (10, 20, 30, 40, 50)
first, *middle, last = numbers
print(first)
print(middle)
print(last)
Output
10
[20, 30, 40]
50
Output explanation: The first and last values go to separate variables, while the middle values are collected into a list.
8.11 Looping Through Tuples
You can use a for loop to visit every item in a tuple one at a time. During each loop cycle, Python places the next tuple item into a loop variable. Looping is useful for displaying values, checking information, calculating totals, or processing fixed records without writing a separate statement for every item.
Example
fruits = ("apple", "banana", "orange")
for fruit in fruits:
print(fruit)
Output
apple
banana
orange
Output explanation: The loop runs three times. Each time, fruit contains the next tuple item and print displays it.
8.12 Joining Tuples
You can join two or more tuples with the plus operator. Python creates a new tuple containing the items from each original tuple in order. The original tuples remain unchanged because tuples are immutable. Joining is useful when separate groups of fixed data need to be combined into one larger collection.
Example
first = (1, 2)
second = (3, 4)
combined = first + second
print(combined)
Output
(1, 2, 3, 4)
Output explanation: Python places the second tuple after the first and stores the result in a new tuple.
8.13 Repeating Tuples
The multiplication operator can repeat all items in a tuple a chosen number of times. Python does not multiply the individual values. Instead, it copies the sequence repeatedly into a new tuple. Repetition is useful for creating patterns, default values, repeated labels, or simple test data in beginner programs.
Example
pattern = ("A", "B")
result = pattern * 3
print(result)
Output
('A', 'B', 'A', 'B', 'A', 'B')
Output explanation: The two-item tuple is repeated three times in the new tuple.
8.14 Tuple Methods
Tuples have two main built-in methods: count and index. The count method tells you how many times a value appears. The index method tells you the position of the first matching value. Tuples have fewer methods than lists because tuple items cannot be added, removed, sorted, or changed directly.
Example
numbers = (5, 10, 5, 20, 5)
print(numbers.count(5))
print(numbers.index(20))
Output
3
3
Output explanation: The value 5 appears three times, and the value 20 is located at index 3.
8.15 Nested Tuples
A nested tuple is a tuple that contains one or more tuples as items. Nested tuples are helpful for organizing rows, coordinates, records, and grouped settings. To access a deeply stored value, use one index for the outer tuple and another index for the inner tuple. Each index moves one level deeper.
Example
students = (("Ali", 80), ("Sara", 95))
print(students[1][0])
print(students[1][1])
Output
Sara
95
Output explanation: Index 1 selects the second inner tuple, and the next indexes select Sara and 95.
8.16 Returning Multiple Values
A Python function can return several values separated by commas. Python automatically packs those values into a tuple. The caller can store the tuple in one variable or unpack it into several variables. This technique is useful when a function needs to provide related results, such as a minimum and maximum or a name and score.
Example
def get_scores():
return 75, 90
math_score, science_score = get_scores()
print(math_score)
print(science_score)
Output
75
90
Output explanation: The function returns two values as a tuple. Unpacking places them into two separate variables.
8.17 Named Tuples
A named tuple is a special tuple whose items can be accessed by meaningful field names as well as indexes. It comes from the collections module. Named tuples remain lightweight and immutable, but they make records easier to understand. They are useful for points, products, students, addresses, or other small fixed records.
Example
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
location = Point(4, 7)
print(location.x)
print(location.y)
Output
4
7
Output explanation: The named tuple stores x and y values, and dot notation accesses each field by name.
8.18 Tuples vs Lists
Lists and tuples both store ordered collections, allow duplicates, and support indexing and slicing. The main difference is that lists are mutable while tuples are immutable. Use a list when values need to change. Use a tuple when the data should remain fixed, protected, and clear in meaning throughout the program.
Example
shopping_list = ["milk", "bread"]
coordinates = (43.7, -79.4)
shopping_list.append("eggs")
print(shopping_list)
print(coordinates)
Output
['milk', 'bread', 'eggs']
(43.7, -79.4)
Output explanation: The list changes by adding eggs, while the tuple remains fixed and is only displayed.
8.19 Performance Considerations
Tuples can use slightly less memory than equivalent lists and may be a little faster to create or read. The difference is usually small in beginner programs, so clarity is more important than tiny performance gains. Choose tuples mainly when values should not change, not only because you expect the program to become faster.
Example
fixed_days = ("Monday", "Tuesday", "Wednesday")
print(len(fixed_days))
print(fixed_days[0])
Output
3
Monday
Output explanation: Python reports three items and then accesses the first fixed value, Monday.
8.20 Practical Tuple Applications
Tuples are practical for values that naturally belong together and should remain fixed. Common examples include map coordinates, RGB colors, calendar dates, database records, dimensions, and function results. A tuple clearly communicates that the grouped values represent one stable record rather than a collection that will be edited repeatedly.
Example
rgb_color = (255, 165, 0)
red, green, blue = rgb_color
print(red)
print(green)
print(blue)
Output
255
165
0
Output explanation: The RGB tuple is unpacked into separate red, green, and blue values, which are printed one per line.
8.21 Chapter Practice Exercises
Practice exercises help you remember tuple syntax and understand when tuples are useful. In this section, you will create tuples, access items, use negative indexes, slice ranges, unpack values, loop through items, join tuples, and apply tuple methods. Try each task before reading or running the sample solution so that you develop problem-solving confidence.
Example
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
print(days[0])
print(days[-1])
print(days[1:4])
print(len(days))
Output
Mon
Fri
('Tue', 'Wed', 'Thu')
5
Output explanation: The program prints the first item, last item, a middle slice, and the total number of items.
8.22 Chapter Mini Project
This mini project combines tuple creation, nested tuples, looping, unpacking, and calculations. The program stores product records as fixed tuples inside a larger tuple. Each record contains a product name, price, and quantity. The loop unpacks every record, calculates its subtotal, prints the details, and adds the subtotal to the final order total.
Example
products = (
("Notebook", 4.50, 2),
("Pen", 1.25, 3),
("Folder", 2.00, 1)
)
total = 0
for name, price, quantity in products:
subtotal = price * quantity
total += subtotal
print(name, "=", subtotal)
print("Total =", total)
Output
Notebook = 9.0
Pen = 3.75
Folder = 2.0
Total = 14.75
Output explanation: Each product tuple is unpacked into name, price, and quantity. The program calculates every subtotal and then prints the complete total of 14.75.