Python Learning Session-09: Tuples in Python – Immutable
Collections!
👋 Welcome Back!
We’ve learned about lists, which are flexible and
allow changes. But what if you need a collection that should never change?
That’s where Tuples come in. Tuples are like lists, but with one big
difference: they are immutable.
✅ What is a Tuple?
A tuple is an ordered collection of items, just like
a list, but you cannot modify it after creation.
✔ Why use tuples?
- Protect
data from accidental changes.
- Faster
than lists (because they’re immutable).
- Commonly
used for fixed data like coordinates, dates, or configuration settings.
✅ Creating Tuples
Tuples use parentheses ():
Python
# Example of a tuple
colors = ("red", "green",
"blue")
print(colors)
Show more lines
✔ You can also create a tuple
without parentheses:
Python
numbers = 1, 2, 3
Show more lines
✅ Accessing Tuple Elements
Just like lists, tuples use indexing:
Python
print(colors[0]) # red
print(colors[-1]) # blue
Show more lines
✅ Immutability in Action
Try changing a tuple:
Python
colors[0] = "yellow" # ❌
Error: 'tuple' object does not support item assignment
Show more lines
✔ Why important? Tuples
are perfect for data that should remain constant.
✅ Tuple Operations
- Concatenation
Python
tuple1 = (1, 2)
tuple2 = (3, 4)
print(tuple1 + tuple2) # (1, 2, 3, 4)
Show more lines
- Repetition
Python
print(tuple1 * 3) # (1, 2, 1, 2, 1, 2)
Show more lines
✅ Looping Through Tuples
Python
for color in colors:
print(color)
Show more lines
✅ Tuple Methods
- count(value)
→ Count occurrences
- index(value)
→ Find position of value
Python
numbers = (1, 2, 2, 3)
print(numbers.count(2)) # 2
print(numbers.index(3)) # 3
Show more lines
✅ Nested Tuples
Tuples can contain other tuples:
Python
nested = ((1, 2), (3, 4))
print(nested[0][1]) # 2
Show more lines
✅ Summary
Tuples are simple, fast, and secure. Use them when you need fixed
data that should never change.
🔥 Challenge for You
Create a tuple of 5 cities. Print them one by one. Then, try
adding a new city and see what happens!
👉 Next Session: Session-10:
Sets in Python – Unique Collections!
No comments:
Post a Comment