๐ฏ Learning Objectives
By the end of this lesson, learners will be able to:
-
Define and create tuples
-
Understand the concept of immutability
-
Access tuple items using indexing
-
Compare tuples with lists
-
Use tuple unpacking in Python
๐ Lesson Content
๐น What is a Tuple in Python?
A tuple is a collection of items that is:
-
Ordered
-
Immutable (cannot be changed)
-
Can contain mixed data types
-
Created using parentheses
()
๐ธ Creating a Tuple
โ You can use tuples to store any type of values:
If it’s a single-item tuple, donโt forget the comma:
๐ธ Accessing Items in a Tuple
Just like lists, tuples use indexing:
โ Index starts at 0.
๐ธ Immutability: Key Difference from Lists
Tuples cannot be changed after creation.
โ They are read-only, making them more secure and memory-efficient.
๐ธ Tuple Packing and Unpacking
You can assign multiple values to a tuple at once:
This is called unpacking.
๐ Tuple vs List Comparison
Feature | Tuple | List |
---|---|---|
Syntax | () |
[] |
Mutable | โ No (Immutable) | โ Yes |
Performance | โ Faster | Slower |
Use Case | Fixed data | Changing data |
Methods | Limited (count , index ) |
Many (append , remove , etc.) |
๐ง When to Use Tuples
-
When the data should not change
-
For function returns (e.g., coordinates, RGB values)
-
For dictionary keys (lists canโt be used as keys, tuples can)
๐ Assignment
-
Create a tuple of 4 favorite cities.
-
Access and print the second and last city.
-
Try modifying one element (observe the error).
-
Use tuple unpacking to assign each city to a variable and print them.