Loading notes...
Loading notes...
Class 11 • Chapter 9
Chapter 9 introduces Tuples, an immutable sequence data type used to safely store collections of data that must remain constant throughout the program's execution.
Tuples are the third major sequence data type in Python. If a List is like a dynamic, editable document, a Tuple is like a read-only PDF. Tuples store an ordered collection of heterogeneous items, exactly like lists. The critical difference is that Tuples are Immutable. They are used to store data that should never, ever change throughout the execution of a program (like the days of the week, or the RGB color code for Red).
9.1 Creating Tuples
Tuples are typically created by placing elements inside parentheses `()`, separated by commas. However, the parentheses are actually optional; it is the COMMAS that define a tuple.
# Creating a standard tuple
colors = ("Red", "Green", "Blue")
# Creating a tuple without parentheses (Tuple Packing)
coordinates = 10.5, 20.8, -5.0
# CRITICAL: Creating a tuple with a SINGLE element requires a trailing comma
single_tuple = (50,) # This is a tuple
not_a_tuple = (50) # Python treats this as just the integer 50 inside math parentheses9.2 Accessing Elements
Because Tuples are ordered sequences, accessing their elements uses the exact same indexing and slicing mechanics as Strings and Lists.
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[0]) # Output: 10
print(my_tuple[-1]) # Output: 50
print(my_tuple[1:4]) # Output: (20, 30, 40)9.3 Tuple Immutability
Tuples cannot be changed once created. You cannot assign a new value to an existing index, nor can you use methods like `append()`, `insert()`, or `remove()`. If you try, Python throws a TypeError.
colors = ("Red", "Green", "Blue")
# colors[0] = "Yellow" <-- THIS WILL CRASH THE PROGRAM!
# If you absolutely MUST change a tuple, the workaround is converting it to a list first:
temp_list = list(colors)
temp_list[0] = "Yellow"
colors = tuple(temp_list) # Re-pack it into a new tuple object9.4 Tuple Unpacking
Tuple Unpacking is an incredibly powerful Python feature that allows you to extract elements from a tuple and assign them directly to multiple variables in a single, clean line of code.
student_data = ("Basant", 17, "BCA")
# Unpacking the tuple into three separate variables
name, age, course = student_data
print("Name:", name) # Output: Basant
print("Course:", course) # Output: BCA9.5 Why use Tuples instead of Lists?
If Tuples are just 'locked' lists, why use them?