Python Notes
Python Tuples का complete guide – immutability, creation, packing/unpacking, named tuples, tuple vs list comparison, use cases, और interview questions हिंदी में।
Introduction (परिचय)
Tuple एक ordered, immutable sequence है। एक बार बनाने के बाद इसके elements change नहीं किए जा सकते।
Key Properties: - 🔒 Immutable – Create होने के बाद elements बदल नहीं सकते - ✅ Ordered – Elements का order maintain होता है - ✅ Allows Duplicates - ✅ Heterogeneous – Different types allowed - ✅ Hashable – Dictionary key बन सकती है (if all elements hashable) - ⚡ Faster than List – Less overhead
2. Indexing and Slicing
Tuple indexing और slicing exactly list जैसी है।
Output:
3. Immutability (अपरिवर्तनीयता)
Output:
| Error | 'tuple' object does not support item assignment |
| Error | 'tuple' object doesn't support item deletion |
| Error | 'tuple' object has no attribute 'append' |
4. Tuple Packing & Unpacking
Python की सबसे powerful features में से एक।
Output:
5. Tuple Methods (Only 2!)
Tuples के पास सिर्फ 2 methods हैं (immutable होने के कारण):
nums = (1, 2, 3, 2, 4, 2, 5, 1)
# count() – occurrences गिनना
print(nums.count(2)) # 3
print(nums.count(1)) # 2
print(nums.count(9)) # 0
# index() – पहली occurrence का index
print(nums.index(2)) # 1
print(nums.index(1)) # 0
# index with start and end
print(nums.index(2, 2)) # 3 (index 2 से search)
print(nums.index(2, 2, 6)) # 3 (index 2-5 में search)
# ValueError if not found
try:
nums.index(99)
except ValueError:
print("Not found!") # Not found!Output:
Tuple Methods vs List Methods
| Method | Tuple | List |
|---|---|---|
count() | ✅ | ✅ |
index() | ✅ | ✅ |
append() | ❌ | ✅ |
extend() | ❌ | ✅ |
insert() | ❌ | ✅ |
remove() | ❌ | ✅ |
pop() | ❌ | ✅ |
sort() | ❌ | ✅ |
reverse() | ❌ | ✅ |
clear() | ❌ | ✅ |
copy() | ❌ | ✅ |
6. Tuple as Dictionary Key
Tuples hashable हैं (अगर सभी elements hashable हों), इसलिए dictionary keys बन सकती हैं।
Output:
| (0,0) | start |
| (1,0) | path |
| (2,2) | end |
| Error | unhashable type: 'list' |
7. Named Tuples (namedtuple)
collections.namedtuple से readable tuples बनाएं।
Output:
8. Tuple Operations
t1 = (1, 2, 3)
t2 = (4, 5, 6)
# Concatenation (new tuple)
t3 = t1 + t2
print(t3) # (1, 2, 3, 4, 5, 6)
# Repetition
t4 = t1 * 3
print(t4) # (1, 2, 3, 1, 2, 3, 1, 2, 3)
# Membership
print(2 in t1) # True
print(7 in t1) # False
# Length, min, max, sum
nums = (3, 1, 4, 1, 5, 9)
print(len(nums)) # 6
print(min(nums)) # 1
print(max(nums)) # 9
print(sum(nums)) # 23
# Comparison (lexicographic)
print((1, 2, 3) == (1, 2, 3)) # True
print((1, 2, 3) < (1, 2, 4)) # True
print((1, 2) < (1, 2, 3)) # True
# Iteration
for item in (10, 20, 30):
print(item, end=" ") # 10 20 30
print()
# zip with tuple
names = ("Alice", "Bob")
scores = (95, 87)
for name, score in zip(names, scores):
print(f"{name}: {score}")Output:
9. Performance: Tuple vs List
Performance Summary:
| Aspect | Tuple | List |
|---|---|---|
| Memory | Less (~30% less) | More |
| Creation | Faster | Slower |
| Access | Same O(1) | Same O(1) |
| Iteration | Slightly faster | Slightly slower |
| Modification | Not allowed | O(1)/O(n) |
| As dict key | ✅ Yes | ❌ No |
| Thread safety | ✅ Safer | ❌ Needs locking |
10. Use Cases (कब उपयोग करें)
11. Tuple Comprehension? (Generator)
12. Interview Questions (इंटरव्यू प्रश्न)
Q1: Tuple immutable होती है, फिर भी (1, [2, 3], 4) में list change हो सकती है?
हाँ! Tuple immutable का मतलब है tuple के references change नहीं होते। लेकिन अगर एक reference किसी mutable object (list) को point करता है, तो वह object internally change हो सकता है।
Q2: Empty tuple और single-element tuple में क्या difference?
empty = ()
single = (1,) # trailing comma जरूरी
not_tuple = (1) # यह int है!Q3: Tuple को list में और list को tuple में convert?
t = (1, 2, 3)
l = list(t) # tuple → list
t2 = tuple(l) # list → tupleQ4: Why are tuples faster than lists?
Tuples immutable होती हैं, इसलिए Python उन्हें optimize करता है – constant folding (same tuple code में सिर्फ एक बार create होती है), less memory allocation, simpler internal structure।
Q5: Tuple को sort कैसे करें?
t = (3, 1, 4, 1, 5, 9)
sorted_t = tuple(sorted(t)) # (1, 1, 3, 4, 5, 9)
sorted_desc = tuple(sorted(t, reverse=True)) # (9, 5, 4, 3, 1, 1)Q6: Two tuples को merge कैसे करें?
Summary
| Feature | Tuple | List |
|---|---|---|
| Syntax | (1, 2, 3) | [1, 2, 3] |
| Mutable | ❌ No | ✅ Yes |
| Methods | 2 (count, index) | 11+ |
| Hashable | ✅ Yes | ❌ No |
| Memory | Less | More |
| Speed | Faster | Slower |
| Best for | Fixed data, dict keys, function return | Dynamic collections |
🎯 Rule of Thumb: जब data "should not change" तो Tuple use करें – records, coordinates, config values, function return values।
Output Blocks for Remaining Sections
Section 9 Output:
List size: 184 bytes Tuple size: 136 bytes List creation: 0.0732s Tuple creation: 0.0118s
Section 10 Output:
3 2 0 apple 1 banana 2 cherry User 1: Alice <alice@email.com> User 2: Bob <bob@email.com> User 3: Charlie <charlie@email.com> True Name: Alice, Age: 25
Section 11 Output:
<class 'generator'> <generator object <genexpr> at 0x...> (0, 1, 4, 9, 16) (0, 1, 4, 9, 16)
⚠️ Common Mistakes (आम गलतियाँ)
❌ Mistake 1: Single Element Tuple बनाते वक्त comma भूलना
# ❌ WRONG - यह tuple नहीं, integer है!
t = (42)
print(type(t)) # <class 'int'>
# ✅ RIGHT - trailing comma लगाओ
t = (42,)
print(type(t)) # <class 'tuple'><class 'int'> <class 'tuple'>
❌ Mistake 2: Tuple को modify करने की कोशिश
TypeError: 'tuple' object does not support item assignment (99, 2, 3)
❌ Mistake 3: Tuple comprehension समझना
# ❌ यह generator है, tuple नहीं!
result = (x**2 for x in range(5))
print(type(result)) # <class 'generator'>
# ✅ tuple() से wrap करो
result = tuple(x**2 for x in range(5))
print(result) # (0, 1, 4, 9, 16)<class 'generator'> (0, 1, 4, 9, 16)
❌ Mistake 4: Mutable elements inside tuple को safe समझना
(1, [2, 3, 99], 4)
❌ Mistake 5: Unpacking में variable count mismatch
1 [2, 3]
❌ Mistake 6: List with mutable elements को dict key बनाना
{((1, 2), 3): 'value'}❌ Mistake 7: += operator पर confusion
# ❌ यह original tuple modify नहीं करता — new object बनता है!
t = (1, 2, 3)
print(id(t)) # कुछ id
t += (4, 5)
print(id(t)) # DIFFERENT id! (new tuple बना)
print(t) # (1, 2, 3, 4, 5)140234567890 140234567999 (1, 2, 3, 4, 5)
✅ Key Takeaways (मुख्य बातें)
- 🔒 Tuple immutable है — एक बार बनाने के बाद elements add, remove, या change नहीं कर सकते।
- 📦 Tuple packing/unpacking Python की most powerful feature है — swap, multiple return values, और loop destructuring में बहुत काम आती है।
- ⚡ Tuple list से faster और lighter है — ~30% कम memory लेती है और creation ~5x तेज़ होता है।
- 🔑 Tuple hashable है — dictionary keys और set elements बन सकती है (अगर सभी elements hashable हों)।
- 📝 Single element tuple में trailing comma ज़रूरी है —
(42,)tuple है,(42)सिर्फ int! - 🛠️ Tuple के पास सिर्फ 2 methods हैं —
count()औरindex(), क्योंकि modify करने वाली methods की ज़रूरत नहीं। - 🏷️ Named tuples readability बढ़ाती हैं —
point.xबहुत clearer हैpoint[0]से। - 🎭 Mutable objects inside tuple change हो सकते हैं — tuple references को protect करती है, objects को नहीं।
- 🔄 Tuple को "modify" करने के लिए — list में convert करो, change करो, फिर tuple में वापस convert करो।
- 📊 Use tuple when data should not change — coordinates, RGB values, database records, config constants।
❓ FAQ (अक्सर पूछे जाने वाले सवाल)
Q1: Tuple और List में कब कौनसी use करें?
Tuple use करें जब data fixed हो और change नहीं होना चाहिए — जैसे coordinates(x, y), RGB colors(255, 0, 0), database records, function return values। List use करें जब data dynamic हो और add/remove/modify करना हो — जैसे shopping cart, to-do list, growing collections।
Q2: क्या Tuple को sort किया जा सकता है?
हाँ! लेकिन in-place नहीं (.sort()available नहीं)।sorted()function use करें जो new sorted tuple return करता है: ``python t = (3, 1, 4, 1, 5) sorted_t = tuple(sorted(t)) # (1, 1, 3, 4, 5)``
Q3: Tuple में duplicate values allowed हैं?
हाँ! Tuple ordered sequence है, duplicates पूरी तरह allowed हैं: ``python t = (1, 2, 2, 3, 3, 3) print(t.count(3)) # 3 ``Q4: Tuple hashable कब नहीं होती?
जब tuple के अंदर कोई mutable (unhashable) element हो — जैसे list: ``python t = (1, [2, 3]) # यह hashable नहीं है! # hash(t) → TypeError: unhashable type: 'list' ``Q5: namedtuple और regular class में क्या difference है?
namedtuple lightweight, immutable, और memory-efficient है। Regular class में methods, inheritance, mutability सब मिलता है। जब simple data container चाहिए (no methods), namedtuple best है। Complex behavior के लिए class use करें।Q6: Tuple अंदर list change हो सकती है — तो immutable का मतलब क्या?
Immutable = tuple object itself change नहीं होता — यानी references fixed रहते हैं। लेकिन अगर reference किसी mutable object (list) को point करता है, तो वो object अपने अंदर change हो सकता है। Analogy: आपके घर का address fix है (tuple), लेकिन घर के अंदर furniture रख/हटा सकते हो (list)।
Q7: Python internally tuples को कैसे optimize करता है?
Python tuples के लिए constant folding करता है — अगर code में same tuple बार-बार बनती है तो एक ही object reuse होता है। साथ ही small tuples (length 0-20) को free list में cache करता है, जिससे creation/deletion faster होता है।
Q8: *args function parameter tuple क्यों होता है?
*argstuple इसलिए होता है क्योंकि function arguments fixed होने चाहिए — accidentally modify नहीं होना चाहिए। Tuple immutability गारंटी देती है कि function body मेंargssafely iterate हो सकता है बिना किसी side-effect के।
🎯 Interview Questions (Detailed)
Q1: Tuple और List में fundamental difference क्या है? कब कौनसी use करें?
Answer: Tuple immutable और List mutable है। Tuple use करें जब data fixed हो (coordinates, configs, dict keys)। List use करें जब dynamic collection चाहिए। Tuple faster है, less memory लेती है, और hashable है (dict key बन सकती है)। List versatile है — append, remove, sort सब support करती है।
Q2: (1) और (1,) में क्या difference है? Explain with type.
Answer:(1)एक integer है — parentheses यहाँ grouping operator हैं।(1,)एक tuple है — trailing comma tuple बनाती है।type((1))→<class 'int'>,type((1,))→<class 'tuple'>। यह Python interviews में बहुत common trick question है।
Q3: Tuple immutable है फिर भी t = (1, [2,3], 4) में t[1].append(5) कैसे work करता है?
Answer: Tuple की immutability means — tuple के references (pointers) change नहीं होते। t[1] हमेशा same list object को point करेगा। लेकिन वो list object internally mutable है, इसलिए उसके अंदर changes हो सकते हैं। Tuple guarantee करती है "कौन-कौन से objects हैं" — not "objects के अंदर क्या है"।Q4: Tuple को dictionary key क्यों बना सकते हैं लेकिन list को नहीं?
Answer: Dictionary keys hashable होनी चाहिए। Hashable = object की lifetime में hash value change नहीं होनी चाहिए। Tuple immutable है → hash stable रहता है → dict key बन सकती है। List mutable है → elements change होने पर hash बदल जाएगा → dict key नहीं बन सकती। Exception: अगर tuple में list है (1, [2,3]), तो यह tuple भी unhashable होगी!Q5: Python internally tuples को lists से differently कैसे store करता है?
Answer: List internally variable-size array maintain करती है (over-allocation for amortized O(1) append)। Tuple fixed-size है — exactly उतनी memory allocate होती है जितने elements हैं। Tuple creation में CPython tuple free-list use करता है (small tuples cache होती हैं), और constant folding से compile-time पर same tuples reuse होती हैं। इसीलिए tuple ~30% कम memory लेती है।
Q6: *args tuple क्यों होता है? list भी हो सकता था।
Answer: Design decision — function arguments modify नहीं होने चाहिए accidentally। Tuple immutable है, जिससे function body में args safe रहते हैं। कोईargs.append()याargs[0] = xaccidentally नहीं कर सकता। यह defensive programming principle follow करता है।
Q7: Tuple packing/unpacking के 3 practical use cases बताओ।
Answer: 1. Variable swap:a, b = b, a— no temp variable needed 2. Multiple return values:def minmax(lst): return min(lst), max(lst)→lo, hi = minmax(data)3. Loop destructuring:for i, (name, score) in enumerate(students):— nested unpacking Bonus: Extended unpacking:first, *rest, last = (1,2,3,4,5)→ head/tail pattern
Q8: namedtuple vs dataclass — कब कौनसी use करें?
Answer:namedtupleuse करें जब simple, immutable, lightweight data container चाहिए (no methods needed, tuple-like behavior)।dataclassuse करें जब mutable objects चाहिए, methods add करने हों, default values चाहिए, या__post_init__logic हो।namedtuplememory-efficient है;dataclassfeature-rich है। Python 3.7+ में dataclass generally preferred है complex cases के लिए।
Q9: Tuple slice करने पर new tuple बनती है या same object?
Answer: Tuple slice always new tuple object बनाती है — event[:]भी new object return करती है (unlike some implementations of strings)। लेकिन elements copy नहीं होते — shallow copy होती है (references same objects को point करते हैं)।t = (1,2,3); s = t[:]→t is scould beTruedue to Python optimization for same content, but generally it's a new object।
Q10: Write a function that flattens nested tuples — ((1,2),(3,(4,5)),6) → (1,2,3,4,5,6)
Answer: ``python def flatten_tuple(t): result = [] for item in t: if isinstance(item, tuple): result.extend(flatten_tuple(item)) else: result.append(item) return tuple(result) nested = ((1, 2), (3, (4, 5)), 6) print(flatten_tuple(nested)) # (1, 2, 3, 4, 5, 6)`Recursive approach —isinstance(item, tuple)` check करके nested tuples को recursively flatten करते हैं।
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Tuples – Immutable Sequences.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, data, structures, tuples
Related Python Master Course Topics