๐ Lesson 8: Python Tuples – Immutable Lists
Welcome back! In this lesson, you’ll learn about tuples — a collection similar to lists but immutable. Once created, tuples cannot be changed, which makes them ideal for storing data that should remain constant.
⭐ What You Will Learn in This Lesson
- What tuples are and how they differ from lists
- Accessing items in a tuple
- Tuple immutability and common mistakes
- Tuple operations and membership checks
- Packing and unpacking tuples for multiple values
- Practical uses of tuples in Python programs
๐ฆ What Is a Tuple?
A tuple is an ordered, immutable collection of items. You cannot change its contents once it’s created.
my_tuple = ("apple", "banana", "cherry")
print(my_tuple)
๐ง Output
('apple', 'banana', 'cherry')
๐พ Accessing Tuple Items
Use indexing, just like with lists:
print(my_tuple[0]) # apple
print(my_tuple[-1]) # cherry
๐ง Output
apple
cherry
❌ Tuples Are Immutable
You cannot modify tuples after creation:
my_tuple[1] = "blueberry" # ❌ This will cause an error
⚡ Tuple Operations
- Length:
len(my_tuple) - Check if item exists:
"apple" in my_tuple - Loop through a tuple:
for fruit in my_tuple:
print(fruit)
๐ง Output
apple
banana
cherry
๐ Tuple Packing & Unpacking
Store multiple values in a tuple and unpack them into separate variables:
person = ("Alice", 25, "USA")
name, age, country = person
print(name) # Alice
print(age) # 25
print(country) # USA
๐ง Output
Alice
25
USA
๐งฉ Why Use Tuples?
- Data that should not change (coordinates, constants)
- Faster than lists for some operations
- Useful for functions returning multiple values
๐ฅ Who Is This Lesson For?
- Beginners learning Python data structures
- Students wanting immutable storage
- Developers handling constants or multiple return values
❌ Common Mistakes
- Trying to modify a tuple (IndexError / TypeError)
- Confusing tuples with lists
- Unpacking the wrong number of values
❓ Frequently Asked Questions (FAQ)
1. Can tuples contain different data types?
Yes! Tuples can hold strings, numbers, or even other tuples.
2. Can I loop through a tuple?
Yes, just like a list, using a for-loop.
3. Why use tuples instead of lists?
Use tuples for data that should not change, for better performance, or when returning multiple values from a function.
4. Can I add items to a tuple later?
No. Tuples are immutable; if you need to add items, convert it to a list first.
๐งช Practice Exercises
- Create a tuple of your top 5 favorite fruits.
- Print the first and last fruit using indexing.
- Try changing one fruit to see the error (learning purpose).
- Unpack the tuple into separate variables and print each.
+ operator.
๐ What’s Next?
In the next lesson, you’ll learn about dictionaries, which let you store key-value pairs — ideal for organizing data efficiently.
Comments
Post a Comment