
Tuples and Their Iteration
Understanding Tuples
Like lists, tuples hold a collection of different data types. Tuples in Python work like a locked briefcase—you can store multiple items inside, but once locked, you can’t change its contents. This makes them ideal for storing data that must remain unchanged, such as fixed configuration settings or GPS coordinates in a mapping application.
One unique aspect of tuples is that if you create one with a single item, Python won’t recognise it as a tuple unless you add a comma after the item. Tuples provide security and efficiency, making them useful in cases where data integrity is a priority. Tuples are created using parentheses () and each item is separated by a comma.
Creating a Tuple
A tuple can be created simply by enclosing values in parentheses.
numbers = (10, 20, 30)
print(numbers)
If a tuple has only one item, a comma must be added after the value to ensure Python recognises it as a tuple.
single_element = (5,)
print(type(single_element)) # Output: <class 'tuple'>
Iterating Through a Tuple
Python provides an easy way to iterate through tuples using a for loop.
Example of Tuple Iteration
fruits = ("apple", "banana", "cherry")
for fruit in fruits:
print(fruit)
This will output each fruit’s name on a new line.
Tuple Operations
Concatenation
Tuples can be combined using the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4, 5, 6)
Replication
A tuple can be repeated multiple times using the * operator.
repeat_tuple = ("Hello",) * 3
print(repeat_tuple) # Output: ('Hello', 'Hello', 'Hello')
Practical Application
Consider a school where teachers need to store student marks for two semesters. Using tuples, this data can be stored and displayed efficiently.
Example Program
semester1 = (85, 90, 78)
semester2 = (88, 76, 92)
# Displaying the marks
print("First Semester Marks:", semester1)
print("Second Semester Marks:", semester2)
# Combining both semester marks
all_marks = semester1 + semester2
print("All Semester Marks:", all_marks)
This program ensures that student marks remain unchanged while allowing efficient retrieval and display.
Conclusion
Tuples in Python provide a secure way to store immutable data. Their read-only nature makes them ideal for preserving data integrity. Iteration using for loops simplifies working with tuples, while operations like concatenation and replication extend their functionality. Tuples are an essential part of Python programming, offering both security and efficiency in handling data.