Tuples & Sequences
টাপল ও সিকোয়েন্স — পরিবর্তন করা যায় না বলেই শক্তিশালী
1. Tuples: Lists That Promise Not to Change
A tuple is an ordered sequence of values, just like a list — but immutable. Once created, you can never add, remove, or replace items. That constraint turns out to be a feature, not a limitation: immutable values are safer to share, can be used as dictionary keys or set members, and signal intent clearly in code.
2. Creating Tuples
# With parentheses — the common form
point = (3, 5)
print(point, type(point))
# Parentheses are optional — it is the comma that creates a tuple
rgb = 255, 128, 0
print(rgb)
# Single-element tuple needs a trailing comma!
single = (42,)
print(type(single)) # tuple
not_a_tuple = (42)
print(type(not_a_tuple)) # int
# Empty tuple
empty = ()
print(len(empty))
# From an iterable
t = tuple([1, 2, 3])
print(t)
3. Immutability Has Real Benefits
Immutability means a tuple's contents cannot change. The name binding can be reassigned (that is just a name change), but the underlying tuple is fixed forever.
t = (1, 2, 3)
# Access works just like a list
print(t[0], t[-1])
# Slicing works and returns a new tuple
print(t[1:])
# Modification raises TypeError
try:
t[0] = 99
except TypeError as e:
print("Error:", e)
# Tuples can be dict keys — lists cannot
locations = {(23.78, 90.40): "Dhaka", (22.35, 91.82): "Chittagong"}
print(locations[(23.78, 90.40)])
4. Unpacking — Where Tuples Shine
Python's unpacking is built on tuples. You use it every day whether you realize it or not.
# Return multiple values — in Python it's really one tuple
def min_max(numbers):
return min(numbers), max(numbers)
lo, hi = min_max([3, 1, 7, 4, 9, 2])
print(f"lo={lo}, hi={hi}")
# Iterating pairs with enumerate (each pair is a tuple)
for i, name in enumerate(["Asif", "Mou", "Rafi"]):
print(i, name)
# Starred unpacking
first, *middle, last = (10, 20, 30, 40, 50)
print(first, middle, last)
5. Named Tuples — Self-Documenting Records
Plain tuples are great for small pairs, but employee[2] does not tell you much.
collections.namedtuple (and the newer typing.NamedTuple) give you field names
while keeping tuple immutability and efficiency.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 5)
print(p) # Point(x=3, y=5)
print(p.x, p.y) # attribute access
print(p[0]) # index access still works
# Still immutable
try:
p.x = 99
except AttributeError as e:
print("locked:", e)
6. Tuples vs Lists — When to Use Which
| Use tuple when... | Use list when... |
|---|---|
| Returning multiple values from a function | Data grows or shrinks over time |
| Values are a fixed, heterogeneous record (x, y, z) | Values are homogeneous (many of the same kind) |
| You need to use it as a dict key | You will sort or reorder items |
| You want to signal "this shouldn't change" | You will append, extend, or pop |
7. Vocabulary (শব্দভাণ্ডার)
| Term | Meaning | বাংলায় |
|---|---|---|
| Sequence | An ordered collection (list, tuple, str, range). | ক্রমযুক্ত সংগ্রহ (list, tuple, str, range)। |
| Immutable | Cannot change after creation. | তৈরির পর আর পরিবর্তন হয় না। |
| Hashable | Can be a dict key or set member. | dict key বা set member হতে পারে। |
| Unpacking | Assigning multiple names from a sequence. | একটি sequence থেকে একাধিক নামে মান bind করা। |
| namedtuple | A tuple with named fields. | নামযুক্ত field-বিশিষ্ট tuple। |
8. Practice Problems
-
Create a tuple of 5 city names, print the third one, and its length.৫টি শহরের নাম দিয়ে tuple তৈরি করুন; তৃতীয়টি ও মোট কতটি তা প্রিন্ট করুন।
✨ Show Answer (উত্তর দেখুন)
ans1.pycities = ("Dhaka", "Chittagong", "Khulna", "Sylhet", "Rajshahi") print(cities[2]) print(len(cities)) -
Write a function
divmod2(a, b)that returns both quotient and remainder as a tuple, and unpack it.একটি ফাংশন লিখুন যা quotient ও remainder একসাথে tuple হিসেবে return করবে।✨ Show Answer (উত্তর দেখুন)
ans2.pydef divmod2(a, b): return a // b, a % b q, r = divmod2(17, 5) print(f"{q=}, {r=}") -
Build a named tuple
Student(name, roll, cgpa)and create a list of three students.Student(name, roll, cgpa)নামক namedtuple বানিয়ে ৩ জন শিক্ষার্থীর list তৈরি করুন।✨ Show Answer (উত্তর দেখুন)
ans3.pyfrom collections import namedtuple Student = namedtuple("Student", ["name", "roll", "cgpa"]) roster = [Student("Asif", 101, 3.85), Student("Mou", 102, 3.92), Student("Rafi", 103, 3.77)] for s in roster: print(f"{s.roll} {s.name:<6} CGPA {s.cgpa}") -
Explain why lists cannot be used as dictionary keys but tuples can.ব্যাখ্যা করুন — dict-এর key হিসেবে list কেন ব্যবহার করা যায় না, কিন্তু tuple যায়।
✨ Show Answer (উত্তর দেখুন)
Answer: Dict keys must be hashable — their hash must stay the same for the lifetime of the key. Lists are mutable, so their hash could change, breaking the dict's internal table. Tuples (of hashable elements) are immutable, so their hash is stable and safe.
Dict-এর key-কে hashable হতে হয় — অর্থাৎ hash-এর মান সবসময় একই থাকতে হয়। List mutable, তাই এর hash পরিবর্তন হতে পারে এবং dict-এর table ভেঙে যেতে পারে। Tuple immutable, তাই এর hash স্থির ও নিরাপদ।
-
Swap two variables using tuple packing/unpacking, and explain what happens step by step.Tuple packing/unpacking দিয়ে দুটি variable swap করুন এবং ধাপে ধাপে ব্যাখ্যা দিন।
✨ Show Answer (উত্তর দেখুন)
ans5.pya, b = 3, 7 a, b = b, a print(a, b) # Step 1: right-hand side `b, a` creates the tuple (7, 3) # Step 2: left-hand side unpacks: a = 7, b = 3
Summary — Module 15
A tuple is an immutable sequence. Parentheses are optional — it is the comma that builds the tuple. Immutability
enables tuples to serve as dict keys and as hashable records. When readability matters, namedtuple adds
field names without giving up tuple efficiency. Use tuples for fixed records and multi-value returns; reach for lists
when the data will grow or change.
namedtuple নামসহ field দেয়। স্থির record ও multi-value return-এ tuple ব্যবহার করুন; data বাড়বে/পরিবর্তিত হবে এমন হলে list।